我需要帮助解决这个问题。查看以下正则表达式:
Pattern pattern = Pattern.compile("[A-Za-z]+(\\-[A-Za-z]+)");
Matcher matcher = pattern.matcher(s1);
我想查找这样的词:“home-made”、“aaaa-bbb”而不是“aaa - bbb”,但不是 “aaa--aa--aaa”。基本上,我想要以下内容:
单词 - 连字符 - 单词。
它适用于一切,除了这个模式会通过:“aaa--aaa--aaa”而不应该。哪种正则表达式适用于此模式?
最佳答案
可以删除表达式中的反斜杠:
"[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()
来检查完整的字符串是否匹配。
如果您想使用 Matcher.find()
查看字符串内部,您可以使用表达式
"(^|\\s)[A-Za-z]+-[A-Za-z]+(\\s|$)"
但请注意,这样只会找到由空格分隔的单词(即不会找到像 aaa-bbb.
这样的单词)。要捕获这种情况,您还可以使用回顾和回顾:
"(?<![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 正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7621821/