java - Search for a word in a String -
if looking particular word inside string, example, in string "how you" looking "are". regular indexof() work faster , better or regex match()
string teststr = "how you"; string lookup = "are"; //method1 if (teststr.indexof(lookup) != -1) { system.out.println("found!"); } //or //method 2 if (teststr.match(".*"+lookup+".*")) { system.out.println("found!"); }
which of 2 methods above better way of looking string inside string? or there better alternative?
- ivard
if don't care whether it's entire word you're matching, indexof()
lot faster.
if, on other hand, need able differentiate between are
, harebrained
, aren't
etc., need regex: \bare\b
match are
entire word (\\bare\\b
in java).
\b
word boundary anchor, , matches empty space between alphanumeric character (letter, digit, or underscore) , non-alphanumeric character.
caveat: means if search term isn't word (let's you're looking ###
), these word boundary anchors match in string aaa###zzz
, not in +++###+++
.
further caveat: java has default limited worldview on constitutes alphanumeric character. ascii letters/digits (plus underscore) count here, word boundary anchors fail on words élève
, relevé
or ärgern
. read more (and how solve problem) here.
Comments
Post a Comment