简体   繁体   English

使用reg exp查找单词

[英]Find word using reg exp

In a string that includes numeric values like: 在包含数字值的字符串中,例如:

6.1, 6.1.1, 6.1.2. 6.1、6.1.1、6.1.2。

I want to find (and replace) the whole word "6.1" and ignore other words starting with "6.1" . 我想查找(并替换)整个单词"6.1"而忽略其他以"6.1"开头的单词。 I tried using \\b in my reg expression: 我尝试在reg表达式中使用\\b

Dim OrginalString as String  = "Sample text with numeric values starting with 6.1 followed by 6.1.1, 6.1.2 "
Dim wordToFind as String = "6.1"
Dim pattern As String = [String].Format("\b({0})\b", wordToFind)
Dim ret As String = Regex.Replace(OrginalString, pattern, "1234",RegexOptions.IgnoreCase)

But it replaces all of the numeric "words" starting with "6.1" . 但是它将替换所有以"6.1"开头的数字“单词"6.1" Here is the result: 结果如下:

ret = "Sample text with numeric values starting with 1234 followed by 1234.1, 1234.2 "

Solutions in VB or C# is OK with me. VB或C#中的解决方案对我来说还可以。

It worked. 有效。 :) Thank you Casimir et Hippolyte! :)谢谢Casimir et Hippolyte!

You can use a negative lookahead: 您可以使用否定的前瞻:

6\.1(?![.\d])

(?!...) means "not followed by" and is only a check, not a part of the match result. (?!...)意思是“不跟随”,仅是检查,而不是比赛结果的一部分。

Note: \\b is only relative to the \\w character class, since the . 注意: \\b仅相对于\\w字符类,因为. isn't in this class, there is a word boundary between 1 and .2 in 6.1.2 不是此类,在6.1.2 1.2之间存在单词边界

You can add a lookbehind to be sure that your number is preceded with a space or the start of the string, example: 您可以在后面添加一个后缀,以确保您的数字前面带有空格或字符串的开头,例如:

(?<=^|\s)6\.1(?![.\d])

or not preceded with a number or a dot: 或前面没有数字或点:

(?<![.\d])6\.1(?![.\d])

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

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