【发布时间】:2011-07-21 17:22:23
【问题描述】:
input1="caused/VBN by/IN thyroid disorder"
要求:查找单词"caused",该单词后跟斜线,后跟任意数量的大写字母——并且后面不跟空格+"by/IN。
在上面的例子中,"caused/VBN" 后面跟着" by/IN",所以 'caused' 不应该匹配。
input2="caused/VBN thyroid disorder"
"by/IN" 不跟随导致,所以它应该匹配
regex="caused/[A-Z]+(?![\\s]+by/IN)"
caused/[A-Z]+ -- 单词 'caused' + / + 一个或多个大写字母(?![\\s]+by) -- 负前瞻 - 不匹配空格和 by
下面是我用来测试的一个简单方法
public static void main(String[] args){
String input = "caused/VBN by/IN thyroid disorder";
String regex = "caused/[A-Z]+(?![\\s]+by/IN)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while(matcher.find()){
System.out.println(matcher.group());
}
输出:caused/VB
我不明白为什么我的负前瞻正则表达式不起作用。
【问题讨论】:
标签: java regex regex-negation regex-lookarounds