Java Regex: Match any word from pattern -
i'm trying implement search function. user types phrase , want match word phrase , phrase in array of strings. problem phrase stored in variable, pattern.compile method won't interpret special characters.
i'm using following flags compile method:
pattern.case_insensitive | pattern.unicode_case | pattern.literal | pattern.multiline
how achieve desired result?
thanks in advance.
edit: example, phrase:
"dog cats donuts"
would result in pattern:
dogs | cats | donuts | dogs cats donuts
- split user-specified phrase
\s+into, say,arr. build following pattern:
"\\b(?:" + pattern.quote(arr[0]) + "|" + pattern.quote(arr[1]) + "|" + pattern.quote(arr[2]) + ... + "\\b"
compile without
pattern.literaloption.
in other words, if want patterns match words in user-specified phrase, have use alternation (the pipes) 1 of words can considered match. however, using pattern.literal option makes alternation operators literal—therefore have "literalize" words themselves, using pattern.quote(...) method. \\b word boundaries not match, say, word in user's phrase "bar" when encountering text "barrage".
edit. in response edit. if want match longest possible match, e.g. not "dogs" , "cats" , "donuts" rather "dogs cats donuts", should place complete phrase in beginning of alternation series, e.g.
\\b(dogs cats donuts|dogs|cats|donuts)\\b
Comments
Post a Comment