c# - Match <keyword> with whitespace at end/start of line -
i can't figure out how c# regex ismatch
match <keyword>
followed end of line or whitespace.
i have [\s]+keyword[\s]+
works spaces, not work keyword<end of string>
or <start of string>keyword
.
i have tried [\s^]+keyword[\s$]+
, makes fail match spaces, , doesn't work @ end or start of string.
here's code tried:
string pattern = string.format("[\\s^]+{0}[\\s$]+",keyword); if(regex.ismatch(text, pattern, regexoptions.ignorecase))
the problem ^
, $
inside character classes not treated anchors literal characters. use alternation instead of character class:
string pattern = string.format(@"(?:\s|^){0}(?:\s|$)",keyword);
note there no need +
, because want make sure if there 1 space. don't care if there more of them. ?:
practice , suppresses capturing don't need here. , @
makes string verbatim string, don't have double-escape backslashes.
there way, find neater. can use lookarounds, ensure there not non-space character left , right of keyword (yes, double negation, think it). assumption valid if there space-character or if there 1 end of string:
string pattern = string.format(@"(?<!\s){0}(?!\s)",keyword);
this same, might more efficient (you'd have profile certain, though - if matters).
you can use first pattern (with non-inverted logic) (positive) lookarounds:
string pattern = string.format(@"(?<=\s|^){0}(?=\s|$)",keyword);
however, doesn't make difference first pattern, unless want find multiple matches in string.
by way, if keyword
might contain regex meta-characters (like |
, $
, +
, on), make sure escape first using regex.escape