简体   繁体   中英

Regular Expression to split a sting

I have a string like [123,234,321,....]

Can i use a regular expression to extract only the numbers ?

this is the code i am using now

 public static string[] Split()
    {
        string s = "[123,234,345,456,567,678,789,890,100]";
        var temp = s.Replace("[", "").Replace("]", "");
        char[] separator = { ',' };
        return temp.Split(separator);

    }

You can use string.Split for this - no need for a regular expression, though your code can be simplified:

var nums = s.Split('[', ']', ',');

Thought you may want to exclude empty entries in the returned array:

var nums = s.Split(new[] { '[', ']', ',' }, 
                   StringSplitOptions.RemoveEmptyEntries);

There's an overload to Trim() that takes a character.

You could do this.

string s = "[123,234,345,456,567,678,789,890,100]";
var nums = s.Trim('[').Trim(']').Split(',');

If you want to use a regular expression, try:

string s = "[123,234,345,456,567,678,789,890,100]";            
var matches = Regex.Matches(s, @"[0-9]+", RegexOptions.Compiled);   

However, regular expressions tend to make your code less readable, so you might stick with your original approach.

Try with using string.Split method;

string s = "[123,234,345,456,567,678,789,890,100]";
var numbers = s.Split('[',']', ',');
foreach(var i in numbers )
   Console.WriteLine(i);

Here is a DEMO .

EDIT : As Oded mentioned , you may want to use StringSplitOptions.RemoveEmptyEntries also.

string s = "[123,234,345,456,567,678,789,890,100]";
MatchCollection matches = Regex.Matches(s, @"(\d+)[,\]]");
string[] result = matches.OfType<Match>().Select(m => m.Groups[1].Value).ToArray();

Here the @ is used to signify a verbatim string literal and allows the escape character '\\' to be used directly in Regular expression notation without escaping itself "\\".

\\d is a digit, \\d+ mean 1 or more digits. The parenthesis signify a group so (\\d+) means I want a group of digits. (*See group used a little later)

[,\\]] square brackets, in brief, mean choose any one of my element so it will choose either the comma , or a square bracket ] which I had to escape.

So the regular expression will find the expressions of sequential digits followed by a , or ] . The Matches will return the set of matches (which we use because there are multiple set) then we go through each match - with some LINQ - and grab the index 1 group which is the second group, "But we only made one group?" We only specified one group, the first group (index 0) is the entire regular expression match, which in our case, will include the , or ] which we don't want.

while you can and probably should use string.Split as other answers indicate, the question specifically asks if you can do it with regex, and yes, you can :-

var r = new Regex(@"\d+", RegexOptions.Compiled );
var matches = r.Matches("[123,234,345,456,567,678,789,890,100]");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM