My string structure is following
characters 1-3 are uppercase alphabets including diacritics such Ň Ö Ï
Characters 4-7 will always be numbers.
8th is space
9th is forward slash
10th space
11th onwards are number.
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"
I wanted replace first 3 characters such as
replaceAll("[2]", "Z")
.replaceAll("[0]", "O")
.replaceAll("[5]", "S")
.replaceAll(" // ","Ï) // replace space forward_slash space with Ï
and position where numbers with following
.replaceAll("(?i)L|(?i)I", "1")
.replaceAll("(?i)o", "0")
.replaceAll("(?i)s", "5")
.replaceAll("(?i)z", "2")
1 Answer 1
I'd say its easier without regex, since you want to replace Strings, but only when they are at certain Positions:
Check, if / is somwere in the first 7 chars, and replace it with Ï:
if(input.indexOf(" / ") < 7 ){
input = input.replaceFirst(" / ", "Ï");
}
Then all your Strings have the same length. Cut them now into the Number/Letter Part and replace everything you want:
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");
Then put everything together again:
String result = letterPart + numberPart + rest;
\p{Lu}might help you with uppercase latin letters. See regular-expressions.info/unicode.html