Word detection followed by a period or space using a regular expression

I use regexand C#to find occurrences of a specific word using

Regex regex = new Regex(@"\b" + word + @"\b");

How can I change my regular expression only to detect a word if it is preceded by spaces and then a space or dot with a dot?

Examples:

this.Button.Value - must match this.value - must match

document.thisButton.Value - should not match

+4
source share
4 answers

You can use search queries and alternation to check two possibilities when a keyword is enclosed in spaces or simply follows with a period:

var line = "this.Button.Value\nthis.value\ndocument.thisButton.Value";
var word = "this";
var rx =new Regex(string.Format(@"(?<=\s)\b{0}\b(?=\s)|\b{0}\b(?=\.)", word));
var result = rx.Replace(line, "NEW_WORD");
Console.WriteLine(result);

IDEONE - regex.

:

  • (?<=\s)\bthis\b(?=\s) - "this", (?<=\s), (?=\s)
  • | -
  • \bthis\b(?=\.) - "this", . ((?=\.))

( , ), , , .

+1
Regex regex = new Regex(@"((?<=( \.))" + word + @"\b)" + "|" + @"(\b" + word + @"[ .])");

, , word , . , word - .

+1

If I understand you correctly:

Regex regex = new Regex(@"\b" + (word " " || ".") + @"\b");
+1
source

The compliance group (?<=...)checks the previous ones and (?=...)checks for the presence of the following, without including them in the match.

Regex regex = new Regex(@"(?<=\s)\b" + word + @"\b|\b" + word + @"\b(?=[\s\.])");

EDIT: Updated template.

EDIT 2: Online Test: http://ideone.com/RXRQM5

0
source

All Articles