简体   繁体   English

正则表达式模式帮助

[英]Regex Pattern Help

I will have the following possible strings: 我将有以下可能的字符串:

12_3 12_3

or 要么

12_3+14_1+16_3-400_2 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. 数字可能不同,但我正在寻找的是X_X数字模式。 However, I need to do a replace that will search for 2_3 and NOT return the 12_3 as a valid match. 但是,我需要进行替换,搜索2_3并且不将12_3作为有效匹配返回。

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_3, and if I pass in 2_3, it would NOT return a match. 他们也需要ARENT(在第一个例子中)..所以,我可能想要检查一个只有12_3的字符串,如果我传入2_3,它将不会返回匹配。 Only if I passed in 12_3. 只有我通过了12_3。

This is for a C# script. 这是一个C#脚本。

Many thanks for any help!! 非常感谢任何帮助!! I'm regex stupid. 我是正则表达式愚蠢的。

Ok, we have ,ie: 2_3+12_3+14_1+16_3-400_2+2_3 好的,我们有,即:2_3 + 12_3 + 14_1 + 16_3-400_2 + 2_3

regexp #1: 正则表达式#1:

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

Matches Found: 匹配发现:

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

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

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

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

regexp #2: 正则表达式#2:

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

Matches Found: 匹配发现:

[0][0] = 12_3 [0] [0] = 12_3

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

[2][0] = 16_3 [2] [0] = 16_3

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

Is here that what you were looking for? 这是你在寻找什么?

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

\\d is digit and \\b is a zero-width word boundary. \\d是数字, \\b是零宽度字边界。 See this C# regex cheat sheet . 看到这个C#正则表达式备忘单

UPDATE: I just looked for a "C# regex cheat sheet" to verify that \\b was a word boundary (it's \\< and \\> in grep). 更新:我只是找了一个“C#正则表达式备忘单”来验证\\b是一个单词边界(在grep中是\\<\\> )。 That was the first result. 这是第一个结果。 I didn't actually verify the text. 我实际上没有验证文本。 Anyway, I now link to a different cheat sheet. 无论如何,我现在链接到另一个备忘单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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