Regex to match against something that is not a specific substring
I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring.
Example:
// Updated to be correct, thanks @Apocalisp
^foo.*(?<!bar)$
Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters.
I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too.
Thanks to @Kibbee for verifying that this works in C# as well.
我认为在这种情况下,你想要消极的后顾之忧 ,就像这样:
foo.*(?<!bar)
Verified @Apocalisp's answer using:
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("^foo.*(?<!bar)$");
System.out.println(p.matcher("foobar").matches());
System.out.println(p.matcher("fooBLAHbar").matches());
System.out.println(p.matcher("1foo").matches());
System.out.println(p.matcher("fooBLAH-ar").matches());
System.out.println(p.matcher("foo").matches());
System.out.println(p.matcher("foobaz").matches());
}
}
This output the the right answers:
false
false
false
true
true
true
I'm not familiar with Java regex but documentation for the Pattern Class would suggest you could use (?!X) for a non-capturing zero-width negative lookahead (it looks for something that is not X at that postision, without capturing it as a backreference). So you could do:
foo.*(?!bar) // not correct
Update : Apocalisp's right, you want negative lookbehind. (you're checking that what the .* matches doesn't end with bar)
链接地址: http://www.djcxy.com/p/77016.html上一篇: 如何检查字符串是否与Scala中的正则表达式完全匹配?
下一篇: 正则表达式匹配不是特定子字符串的东西