Java正则表达式匹配,但String.replaceAll()不匹配';t替换匹配的子字符串

Java正则表达式匹配,但String.replaceAll()不匹配';t替换匹配的子字符串,java,regex,string,replaceall,Java,Regex,String,Replaceall,这给了我以下输出: public class test { public static void main(String[]args) { String test1 = "Nørrebro, Denmark"; String test2 = "ø"; String regex = new String("^&\\S*;$"); Str

这给了我以下输出:

public class test {
        public static void main(String[]args) {
            String test1 = "Nørrebro, Denmark";
            String test2 = "ø";
            String regex = new String("^&\\S*;$");
            String value = test1.replaceAll(regex,"");
            System.out.println(test2.matches(regex));
            System.out.println(value);
        }
    }

这怎么可能?为什么replaceAll()不注册匹配项

您的正则表达式包括
^
。这使得正则表达式从一开始就匹配

如果你尝试

true
Nørrebro, Denmark

您将得到
false

这是可能的,因为
^&\S*$模式匹配整个
ø字符串,但它不匹配整个
Nø;丹麦雷布罗
string。
^
匹配(此处要求)字符串的开头在
&
之前,并且
$
要求
显示在字符串的右端

仅仅删除
^
$
锚定可能不起作用,因为
\S*
是一种贪婪的模式,它可能会过度匹配,例如在
Nø;雷布罗

您可以使用
&\w+
&\S+模式,例如:

test1.matches(regex)


&\w+
模式匹配一个
&
,然后匹配任何1+字字符,然后匹配
,字符串中的任意位置
\S*?
匹配除空格以外的任何0+字符。

您需要理解
^
$
的含义

你可能把它们放在那里是因为你想说:

在每个匹配的开始处,我需要一个
&
,然后是0个或更多非空白字符,然后是一个
结尾处编码>

但是,
^
$
并不意味着每个匹配的开始和结束。它表示字符串的开始和结束

因此,您应该从正则表达式中删除
^
$

String test1 = "Nørrebro, Denmark";
String regex = "&\\w+;";
String value = test1.replaceAll(regex,"");
System.out.println(value); // => Nrrebro, Denmark
现在它输出:

String regex = "&\\S*;";

你可能会问:“那么,什么字符指定了比赛的开始和结束?”。好吧,因为你的正则表达式基本上就是你所匹配的模式,正则表达式的开始就是匹配的开始(除非你有lookbehinds)

您可以使用以下正则表达式:
&(.*)

输出:

        String test1 = "Nørrebro, Denmark";
        String test2 = "ø";
        String regex = new String("&(.*?);");
        String value = test1.replaceAll(regex,"");
        System.out.println(test2.matches(regex));
        System.out.println(value);

不清楚问题出在哪里。您的
来自替换test1,而您的
匹配项
正在测试test2。是的,但是test2是test1的子字符串。test2还与regex匹配。据我所知,replaceAll()查找与正则表达式匹配的子字符串,并将其替换为给定的替换项。只有
test2
与正则表达式匹配
test1
不匹配。您的
test2
匹配正则表达式,但前提是它是一个完整的字符串而不是子字符串。检查
$
在正则表达式末尾的含义…子字符串和整个字符串之间的区别是什么?我需要在开头加上“&”字符。它是否应该匹配以“&”开头的子字符串?在
test1
字符串中,
&
不在开头,而是在
N
之后。
        String test1 = "Nørrebro, Denmark";
        String test2 = "ø";
        String regex = new String("&(.*?);");
        String value = test1.replaceAll(regex,"");
        System.out.println(test2.matches(regex));
        System.out.println(value);
true 
Nrrebro, Denmark