regex pick full word only
I need t开发者_JAVA百科o pick only a full word using regex,I don't want to pick a word if its contained in another word, but I do want to pick if it starts/ends with special characters like _test, test.,test/,test.
Example:I dont want to pick if a word is contained in other word like"context" if I am looking for "text". But want it if I am looking for full-text, /text,text.,text_test, text,text's.
EDIT: Since we cant identify the plural forms, I am deleting that part.
First, you will benefit a lot from completing a tutorial such as this: http://www.codeproject.com/KB/dotnet/regextutorial.aspx And Expresso is an excellent free tool for debugging and testing regular expressions.
Second, your expression should probably be something like:
\b([^A-Za-z]|A-Za-z[^A-Za-z]+)(text)([^A-Za-z]|[^A-Za-z]+A-Za-z)\b
\b word boundaries
([^A-Za-z]|A-Za-z[^A-Za-z]+) means "non alpha characters OR alpha characters followed by at least one non-alpha character"
"text" will be matched by subgroup 2.
Again, go through the tutorial above, it's short and you probably could have figured out how to create this expression in the time it's taken to get an answer here.
If you're looking for a word contained in the variable word
I suggest you use
"\\b\\Q" + word + "\\E\\b"
Here's a breakdown:
\b
: A word boundary\Q
: Nothing, but quotes all characters until \E\E
: Nothing, but ends quoting started by \Q
Something like this may do:
Pattern p = Pattern.compile("\\b\\Q" + word + "\\E\\b");
Matcher m = p.matcher("word like \"context\" while looking for \"text\".");
while (m.find())
System.out.println(m.group());
精彩评论