我有一個條件,我必須從字串中替換一些字符(特殊、不可列印和其他特殊字符),如下所述
private static final String NON_ASCII_CHARACTERS = "[^\\x00-\\x7F]";
private static final String ASCII_CONTROL_CHARACTERS = "[\\p{Cntrl}&&[^\r\n\t]]";
private static final String NON_PRINTABLE_CHARACTERS = "\\p{C}";
stringValue.replaceAll(NON_ASCII_CHARACTERS, "").replaceAll(ASCII_CONTROL_CHARACTERS, "")
.replaceAll(NON_PRINTABLE_CHARACTERS, "");
我們可以重構上面的代碼意味著我們可以使用單個“replaceAll”方法并將所有條件放入其中嗎?
有什么辦法請指教。
uj5u.com熱心網友回復:
您可以使用正則運算式或運算子|
private static final String NON_ASCII_CHARACTERS = "[^\\x00-\\x7F]";
private static final String ASCII_CONTROL_CHARACTERS = "[\\p{Cntrl}&&[^\r\n\t]]";
private static final String NON_PRINTABLE_CHARACTERS = "\\p{C}";
public static String process(String stringValue) {
return stringValue.replaceAll(NON_ASCII_CHARACTERS "|" ASCII_CONTROL_CHARACTERS "|" NON_PRINTABLE_CHARACTERS, "");
}
public static void main(String[] args) {
String val = process("A9339a0zzz]3");
System.out.println(val);
}
uj5u.com熱心網友回復:
碼點
除了使用正則運算式之外,您可能會考慮另一種途徑。您可以為每個字符使用代碼點整數,并Character為字符類別使用查詢類。
String input = … ;
String output =
input
.codePoints() // Returns an `IntStream` of code point `int` values.
.filter( codePoint -> ! Character.isISOControl( codePoint ) ) // Filter for the characters you want to keep. Those code points flunking the `Predicate` test will be omitted.
.collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append ) // Convert the `int` code point integers back into characters.
.toString() ; // Make a `String` from the contents of the `StringBuilder`.
該類Character具有許多由Unicode Consortium定義的分類。您可以使用它們將代碼點流縮小到代表所需字符的代碼點。
uj5u.com熱心網友回復:
根據Pattern javadocs,還應該可以將三個字符類模式組合成一個字符類:
private static final String NON_ASCII_CHARACTERS = "[^\\x00-\\x7F]";
private static final String ASCII_CONTROL_CHARACTERS = "[\\p{Cntrl}&&[^\r\n\t]]";
private static final String NON_PRINTABLE_CHARACTERS = "\\p{C}";
變成
private static final String COMBINED =
"[[^\\x00-\\x7F][\\p{Cntrl}&&[^\r\n\t]]\\p{C}]";
或者
private static final String COMBINED =
"[" NON_ASCII_CHARACTERS ASCII_CONTROL_CHARACTERS
NON_PRINTABLE_CHARACTERS "]";
請注意,&&(intersection) 的優先級低于隱式聯合運算子,因此上述所有的[和]元字符都是必需的。
您決定您認為哪個版本更清晰。這是一個見仁見智的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/477426.html
