user1527484
user1527484

Reputation: 67

regex to get value from string

Im trying to get value from string 1-1:0.0.0(123123) Here is code

string str = "\r\n1-1:0.0.0(123123)\r\n";
string patt = @"1-1:0.0.0(\(.*?)\)\s";
Match match = Regex.Match(str, patt,RegexOptions.IgnoreCase);
string v = match.Groups[1].Value;

problem is that i dont get clear value = "(123123"
can someone explain why there is round bracket at beginning ? :/

Upvotes: 0

Views: 128

Answers (4)

Rawling
Rawling

Reputation: 50104

Your opening-round-bracket match \( is inside the start of your capture group (.

Replace (\( with \((.

Also replace 0.0.0 with 0\.0\.0 for good measure.

Upvotes: 3

Nicholas W
Nicholas W

Reputation: 2241

Your capturing group is (\(.*?), that is a pair of parentheses which creates the capturing group, with a content of \(.*? - matching a literal opening parenthesis and a non-greedy sequence of any characters.

Also note that the . characters in your pattern are not matching literal dots, but any character, I point this out since the target string seems to contain dots.

Upvotes: 1

mihirj
mihirj

Reputation: 1219

Your escape character (\( is misplaced:

Please try following

string str = "\r\n1-1:0.0.0(123123)\r\n";
string patt = @"1-1:0.0.0\((.*?)\)\s";
Match match = Regex.Match(str, patt, RegexOptions.IgnoreCase);
string v = match.Groups[1].Value;

This will print

123123

Upvotes: 2

Dirk Vollmar
Dirk Vollmar

Reputation: 176159

The escaping of the parenthesis is not correct.

Change your pattern to the following (note that the backslash is in front of the first opening ():

@"1-1:0.0.0\((.*?)\)\s";

Upvotes: 2

Related Questions