Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中,如何检查单词是以空格或下划线开头,还是以行/字符串开头?_Java_Regex - Fatal编程技术网

在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(?=[_ ]|$)