regex - Finding whole word only in Java string search -
i'm running problem of finding searched pattern within larger pattern in java program. example, i'll try , find for
loops, stumble upon formula
. of suggestions i've found talk using regular expression searches
string regex = "\\b"+keyword+"\\b"; pattern pattern = pattern.compile(regex); matcher matcher = pattern.matcher(searchstring);
or variant of this. issue i'm running i'm crawling through code, not book-like text there spaces on either side of every word. example, miss for(
, find. there clever way find whole words only?
edit: suggestions. how cases in there keyword starts on first entry of string? example,
class vec { public: ... };
where i'm searching class
(or alternatively public
). patterns suggested thanga, austin lee, npinti, , kai iskratsch not work in case. ideas?
in case, issue \b
flag punctuation marks, white spaces , beginning or end of string. opening bracket not fall within of these categories, , omitted.
the easiest way fix replace "\\b"+keyword+"\\b"
"[\\b(]"+keyword+"[\\b)]"
.
in regex syntax, square brackets denote set of regex engine attempt match character contains.
as per this previous question, seem \b
, [\b]
not same. whilst \b
represents word boundary, [\b]
represents backspace character. fix this, replace "\\b"+keyword+"\\b"
"(\b|\()"+keyword+"(\b|\))"
.
Comments
Post a Comment