Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.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/regex/16.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,regex的新特性,并使用以下代码查找单词的结尾/开头是否包含特殊字符 String s = "K-factor:"; String regExp = "^[^<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[0-9_+]*$"; Matcher matcher = Pattern.compile(regExp).matcher(s); while (matcher.find()) {

regex的新特性,并使用以下代码查找单词的结尾/开头是否包含特殊字符

String s = "K-factor:";
        String regExp = "^[^<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[0-9_+]*$";
        Matcher matcher = Pattern.compile(regExp).matcher(s);
        while (matcher.find()) {
            System.out.println("Start: "+ matcher.start());
            System.out.println("End: "+ matcher.end());
            System.out.println("Group: "+ matcher.group());
            s = s.substring(0, matcher.start());
        }
String s=“K-factor:”;
字符串regExp=“^[^{}\”/;:,~!?@$%^=&*\\]\\\\\()\[0-9+]*$”;
Matcher Matcher=Pattern.compile(regExp.Matcher);
while(matcher.find()){
System.out.println(“Start:+matcher.Start());
System.out.println(“End:+matcher.End());
System.out.println(“组:“+matcher.Group());
s=s.substring(0,matcher.start());
}
要查找字符串的开头或结尾是否有任何特殊字符(:在此示例代码中)。正在尝试跳过该字符。
编译时错误和输出都没有。

请注意,正则表达式匹配的整个字符串不包含您在字符类中定义的字符。该字符串与该模式不匹配,因为它包含

你可以考虑将模式分成两个部分,用交替组检查开始或结束时不需要的字符:

String regExp = "^[<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[0-9_+]|[<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[0-9_+]$";
这是Unicode字母识别或仅限-ASCII:

String regExp = "^\\P{Alpha}|\\P{Alpha}$";

如果要匹配开头和结尾处是否有字母以外的字符,请使用
“^\\P{L}|\\P{L}$”
。您的正则表达式不匹配
K-factor
,因为它在结尾处包含
。感谢@WiktorStribiżew工作正常。请将其作为答案发布,以便其他人参考。
String regExp = "^\\P{Alpha}|\\P{Alpha}$";