[英]How to replace an alphabetic character in a string with null in Java?
我需要一個包含混合字符和數字以及分隔符的字符串,掃描它以查找不是數字或小數點的任何內容; 定界符,那么它將被清空。 這是一個例子:
; Pages / sec ; 0 . 1 7 ; 0 ; 0 . 1 3 ; 0 . 0 5 ; 0 . 1 ; 0 . 1 3 ; 0 . 2 5 ; 0 . 0 3 ; 0 . 0 3 ; 0 . 1 ;
該字符串將變為:
;0.17;0;0.13;0.05;0.1;0.13;0.25;0.03;0.03;0.1;
基本上,字符串中唯一剩下的就是“;” 分隔符和分隔符之間的任何整數或浮點數。 刪除任何字符或空格。
String stringToScan = "; Pages / sec ; 0 . 1 7 ; 0 ; 0 . 1 3 ; 0 . 0 5 ; 0 . 1 ; 0 . 1 3 ; 0 . 2 5 ; 0 . 0 3 ; 0 . 0 3 ; 0 . 1 ;"
String resultingString = stringToScan.replace(?, '')
任何幫助表示贊賞。
String src = "; Pages / sec ; 0 . 1 7 ; 0 ; 0 . 1 3 ; 0 . 0 5 ; 0 . 1 ; 0 . 1 3 ; 0 . 2 5 ; 0 . 0 3 ; 0 . 0 3 ; 0 . 1 ; ";
System.out.println(src.replaceAll("[^0-9\\.;]", "").replaceAll(";+", ";"));
正如 Giovani Vercauteren 已經說過的,您需要一個正則表達式。
任何不是數字、點或分號的東西都應該被刪除。
所以:
String resultingString = stringToScan.replaceAll("[^0-9\\.\\;]", "");
您將需要能夠檢測數值,因此您需要一個正則表達式。
接下來,您需要刪除所有空格。
最后,您只需拆分字符串,過濾掉錯誤的標准並將結果連接在一起。
不確定是否真的需要前導分號和結尾分號,但您可以將它們預先/附加到結果中。
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Replacer {
private static final Pattern NUMERIC_ONLY = Pattern.compile("^[-+]?\\d+(\\.\\d+)?$");
private static Predicate<String> isValid = new Predicate<String>() {
@Override
public boolean test(String str) {
return str != null && !str.isEmpty() && NUMERIC_ONLY.matcher(str).matches();
}
};
public static void main(String[] args) {
String str = "; Pages / sec ; 0 . 1 7 ; 0 ; 0 . 1 3 ; 0 . 0 5 ; 0 . 1 ; 0 . 1 3 ; 0 . 2 5 ; 0 . 0 3 ; 0 . 0 3 ; 0 . 1 ;";
System.out.println(formatAndRemoveNonNumeric(str, ";"));
}
public static String formatAndRemoveNonNumeric(String str, String delim) {
return Stream.of(str.replaceAll("\\s+", "").split(delim)).filter(isValid).collect(Collectors.joining(delim));
}
}
結果: 0.17;0;0.13;0.05;0.1;0.13;0.25;0.03;0.03;0.1
我已經為它寫了一個正則表達式。
以下是滿足您要求的解決方案
public static void main(String[] args) {
String stringToScan = "; Pages / sec ; 0 . 1 7 ; 0 ; 0 . 1 3 ; 0 . 0 5 ; 0 . 1 ; 0 . 1 3 ; 0 . 2 5 ; 0 . 0 3 ; 0 . 0 3 ; 0 . 1 ;";
String result = stringToScan.replaceAll("[^0-9\\.\\;]", "");
System.out.println(result);
}
我希望這會有所幫助謝謝...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.