Solved

Splitting String (Square Brackets) (C#)

Posted on 2014-09-25
4
608 Views
Last Modified: 2014-11-18
Hello,

I have string which clook like this:
a [213515]

I need a method to split this string and remove the square bracket. With the above example this would produce two strings
a
213515

The approach would have to be able to handle different lengths
I’ve tried using a regex  snippet:

string pattern = @"(?<=\[)(.*?)(?=\])";
Match output = Regex.Match("str_value", pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);

Open in new window


But this just extracts the contents of the square brackets?
Any suggestions appreciated,
0
Comment
Question by:andyw27
4 Comments
 
LVL 44

Accepted Solution

by:
AndyAinscow earned 500 total points
ID: 40343533
string s = "a [213515]";
            string[] results = s.Split('[');
            results[1] = results[1].TrimEnd(']');

results[0] is "a" and results[1] is "213515"
0
 
LVL 33

Expert Comment

by:ste5an
ID: 40343535
Your description leads me to this solution:

public static void Main()
{
    string input = "a [213515]";
    string[] result = input.Split(' ');
    foreach (string element in result)
    {                
        Console.WriteLine(element.Replace("[", "").Replace("]", ""));
    }

    Console.ReadLine();
}

Open in new window

0
 
LVL 11

Expert Comment

by:louisfr
ID: 40343545
I'd use the following regex:
(.*?) *\[(.*)\]

Open in new window

0
 
LVL 33

Expert Comment

by:sarabande
ID: 40343578
the Split functions accepts all separators as a char array:

string str = "a [123456]";
string [] tokens = str.Split(new Char [] {' ', '[', ']'} );

Open in new window


Sara
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question