在java中,如何检查单词是以空格或下划线开头,还是以行/字符串开头?
我必须检查字符串中是否有特定的单词。 条件是:它以空格或下划线开头和结尾,或者是字符串的开头或结尾。 不区分大小写 以下是我的代码:在java中,如何检查单词是以空格或下划线开头,还是以行/字符串开头?,java,regex,Java,Regex,我必须检查字符串中是否有特定的单词。 条件是:它以空格或下划线开头和结尾,或者是字符串的开头或结尾。 不区分大小写 以下是我的代码: package example; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { // TODO Auto-generated method
package example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "The starting of week";
String t = "[^_ ]the[ _$]";
Pattern p = Pattern.compile(t,Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(test);
if( matcher.find() ){
System.out.println(true);
}
}
}
我做错了什么?问题是[^abc]的语法可以匹配除“a”、“b”或“c”字符以外的任何字符。 您需要将您的模式更改为:
String t = "(^|[_ ])the[ _$]";
请注意,转义“^”字符无效:
String t = "[\\^_ ]the[ _$]";
因为这将被解释为文字字符“^”,而不是输入的开头
编辑:顺便说一下,“$”字符也存在同样的问题,因此您需要:
String t = "(^|[_ ])the([ _]|$)";
使用
(?mi)(?您可以使用此模式\\b\\b
(?mi)(?<=^|[_ ])the(?=[_ ]|$)