hungrycoder
hungrycoder

Reputation: 507

Regex to take values based on multiple checks

I have string

string s="someMethod(999,'xyz')"

and I want to take 999 and xyz in to array. what could be the best possible way instead of splitting it by '(' first and by ',' and then by '\''

Upvotes: 2

Views: 70

Answers (2)

Jerry
Jerry

Reputation: 4408

Try this regex:

^.+?\((.+?),'(.+?)'\)$

$1: 999, $2: xyz

Full code:

Regex r = new Regex(@"^.+?\((.+?),'(.+?)'\)$");
string[] parameters = new string[2];
parameters[0]=r.Match(s).Groups[1].Value;
parameters[1]=r.Match(s).Groups[2].Value;

If you're not sure that there will be single quotes, use '? instead of '

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98740

You don't need to use regex for that.

You can use String.Substring, String.IndexOf and String.Split methods like;

string s = "someMethod(999,'xyz')";
string BetweenBrackets = s.Substring(s.IndexOf("(") + 1, s.IndexOf(")") - s.IndexOf("(") - 1);
string[] array = BetweenBrackets.Split(new char[] { ',', '\'' }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(array[0]); //999
Console.WriteLine(array[1]); //xyz

Here a DEMO.

Upvotes: 2

Related Questions