[英]Java regex space matches $ and * ??
我不了解有關\\ s的Java正則表達式匹配方式的知識。 在下面的簡單類中,\\ s似乎匹配[至少] $和*,這令人擔憂。 當我不包括\\ s時,每個單詞的最后一個字符會被切碎。 而且,正則表達式似乎都沒有在字符串中以“。”結尾。請問有人可以解釋發生了什么嗎?還是將我指向有用的資源?謝謝。
public class SanitizeText {
public static void main(String[] args)
{
String s = "123. ... This is Evil !@#$ Wicked %^&* _ Mean ()+<> and ;:' - Nasty. \\ =\"";
String t = "123. ... This is Evil !@#$ Wicked %^&* _ Mean ()+<> and ;:' - Nasty. \\ =\"";
s = s.replaceAll(".[^\\w\\s.]", " "); // Does the \s match non-space chars? Sees like at least $ and * are matched.
s = s.replaceAll(" {2,}", " ");
t = t.replaceAll(".[^\\w.]", " "); // Why does this regex chopping the trailing char of each word ??
t = t.replaceAll(" {2,}", " ");
System.out.println ("s: " + s);
System.out.println ("t: " + t);
}
}
// produces:
// s: 123. ... This is Evil $ Wicked * _ Mean and Nasty . "
// t: 123 .. Thi i Evi Wicke Mea an Nast "
\\\\s
與非空格字符不匹配。
正則表達式.[^\\\\w\\\\s.]
將匹配Any character, followed by a non-word, non-space, non-period character
。
對我來說,它似乎完全像這樣。
回答為什么這個正則表達式會砍掉每個單詞的結尾字符?
.[^\\\\w.]
匹配任何字符( .
)后跟非單詞,非點字符,並用空格代替。 因此,它匹配單詞中的最后一個字母和后面的空格。
答案\\ s是否匹配非空格字符? 看起來至少$和*是匹配的。
否。您要匹配一個字符( .
),然后是一個非單詞,非空格字符。 所以每次兩個字符。
.[^\\w\\s.]
將匹配
Wicked %^&* _
1. ^^
2. ^^
*
不匹配,因為后面有空格,因此不能替換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.