[英]Java String regex replace
我的字符串結構如下
1-3個字符是大寫字母,包括Ň
字符4-7始終是數字。
第八位是太空
9號是正斜線
第十空間
11號起是數字。
String str1 = "DIW785o / 42"; // expected result "DIW7850 / 42"
String str2 = "QLR357Ï / 11"; // expected result "QLR3571 / 11"
String str3 = "UÜÈ7477 / 00"; // expected result "UÜÈ7477 / 00"
String str4 = "A / P8538 / 28"; // expected result "AÏP8538 / 28"
String str5 = "CV0875Z / 01"; // expected result "CVO8752 / 01"
String str6 = "SW / 2188 / 38"; // expected result "SWÏ2188 / 38"
我想替換前3個字符,例如
replaceAll("[2]", "Z")
.replaceAll("[0]", "O")
.replaceAll("[5]", "S")
.replaceAll(" // ","Ï) // replace space forward_slash space with Ï
以及以下數字的位置
.replaceAll("(?i)L|(?i)I", "1")
.replaceAll("(?i)o", "0")
.replaceAll("(?i)s", "5")
.replaceAll("(?i)z", "2")
我想說不用正則表達式會更容易,因為您要替換字符串,但僅當它們在某些位置時才可以:
檢查時,如果/
是somwere今年前7個字符,並將其替換為Ï
:
if(input.indexOf(" / ") < 7 ){
input = input.replaceFirst(" / ", "Ï");
}
然后,您的所有字符串都具有相同的長度。 現在將它們切成數字/字母部分,並替換您想要的所有內容:
String letterPart = input.substring(0,3);
String numberPart= input.substring(3,7);
String rest = input.substring(7);
letterPart = letterPart.replace("0", "O");
numberPart = numberPart.replace("o", "0");
numberPart = numberPart.replace("Ï", "1");
numberPart = numberPart.replace("Z", "2");
然后再次將所有內容放在一起:
String result = letterPart + numberPart + rest;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.