开发者

Regex Pattern Help

I will have the following possible strings:

12_3

or

12_3+14_1+16_3-400_2

The numbers could be different, but what I'm looking for are the X_X numeric patterns. However, I need to do a replace that will search for 2_3 and NOT return the 12_3 as a valid match.

The +/-'s are arthemtic symbols, and can be any valid value. They also ARENT required (in the example of the first) .. so, I might want to check a string that just has 12_开发者_如何学JAVA3, and if I pass in 2_3, it would NOT return a match. Only if I passed in 12_3.

This is for a C# script.

Many thanks for any help!! I'm regex stupid.


Ok, we have ,i.e.: 2_3+12_3+14_1+16_3-400_2+2_3

regexp #1:

Regex r1 = new Regex(@"\d+(\d_\d)");
MatchCollection mc = r1.Matches(sourcestring);

Matches Found:

[0][0] = 12_3 [0][1] = 2_3

[1][0] = 14_1 [1][1] = 4_1

[2][0] = 16_3 [2][1] = 6_3

[3][0] = 400_2 [3][1] = 0_2

regexp #2:

Regex r2 = new Regex(@"\d+\d_\d");
MatchCollection mc = r2.Matches(sourcestring);

Matches Found:

[0][0] = 12_3

[1][0] = 14_1

[2][0] = 16_3

[3][0] = 400_2

Is here that what you were looking for?


\b\d+_\d+\b.

\d is digit and \b is a zero-width word boundary. See this C# regex cheat sheet.

UPDATE: I just looked for a "C# regex cheat sheet" to verify that \b was a word boundary (it's \< and \> in grep). That was the first result. I didn't actually verify the text. Anyway, I now link to a different cheat sheet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜