Java正则表达式模式 [英] Java regex patterns
问题描述
我需要帮助解决这个问题。请看以下正则表达式:
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);
我想找这样的字:自制,aaaa-bbb和不是aaa - bbb,而是不
aaa - aa - aaa。基本上,我想要以下内容:
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。
word - hyphen - word.
它适用于所有事情,除了这种模式将通过:aaa - aaa - aaa而不应该。什么正则表达式适用于这种模式?
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:
"[A-Za-z]+-[A-Za-z]+"
以下代码应该可以使用
Pattern pattern = Pattern.compile("[A-Za-z]+-[A-Za-z]+");
Matcher matcher = pattern.matcher("aaa-bbb");
match = matcher.matches();
请注意,您可以使用 Matcher.matches()
而不是 Matcher.find()
以检查匹配的完整字符串。
Note that you can use Matcher.matches()
instead of Matcher.find()
in order to check the complete string for a match.
如果相反,你想要使用 Matcher.find()
查看字符串内部你可以使用表达式
If instead you want to look inside a string using Matcher.find()
you can use the expression
"(^|\\s)[A-Za-z]+-[A-Za-z]+(\\s|$)"
但请注意,只会找到以空格分隔的单词(即没有像 aaa-bbb这样的单词。
)。为了捕捉这种情况,你可以使用lookbehinds和lookaheads:
but 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:
"(?<![A-Za-z-])[A-Za-z]+-[A-Za-z]+(?![A-Za-z-])"
将会读取
(?<![A-Za-z-]) // before the match there must not be and A-Z or -
[A-Za-z]+ // the match itself consists of one or more A-Z
- // followed by a -
[A-Za-z]+ // followed by one or more A-Z
(?![A-Za-z-]) // but afterwards not by any A-Z or -
一个例子:
Pattern pattern = Pattern.compile("(?<![A-Za-z-])[A-Za-z]+-[A-Za-z]+(?![A-Za-z-])");
Matcher matcher = pattern.matcher("It is home-made.");
if (matcher.find()) {
System.out.println(matcher.group()); // => home-made
}
这篇关于Java正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!