I need help with this matter. Look at the following regex:
Pattern pattern = Pattern.compile("[A-Za-z]+(\\-[A-Za-z]+)");
Matcher matcher = pattern.matcher(s1);
I want to look for words like this: “home-made”, “aaaa-bbb” and not “aaa – bbb”, but not
“aaa–aa–aaa”. Basically, I want the following:
word – hyphen – word.
It is working for everything, except this pattern will pass: “aaa–aaa–aaa” and shouldn’t. What regex will work for this pattern?
Can can remove the backslash from your expression:
The following code should work then
Note that you can use
Matcher.matches()instead ofMatcher.find()in order to check the complete string for a match.If instead you want to look inside a string using
Matcher.find()you can use the expressionbut note that then only words separated by whitespace will be found (i.e. no words like
aaa-bbb.). To capture also this case you can then use lookbehinds and lookaheads:which will read
An example: