简体   繁体   中英

Find word using reg exp

In a string that includes numeric values like:

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" . I tried using \\b in my reg expression:

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" . 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.

It worked. :) Thank you 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 . isn't in this class, there is a word boundary between 1 and .2 in 6.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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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