简体   繁体   English

Java String正则表达式替换

[英]Java String regex replace

My string structure is following 我的字符串结构如下

characters 1-3 are uppercase alphabets including diacritics such Ň Ö Ï 1-3个字符是大写字母,包括Ň

Characters 4-7 will always be numbers. 字符4-7始终是数字。

8th is space 第八位是太空

9th is forward slash 9号是正斜线

10th space 第十空间

11th onwards are number. 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"

I wanted replace first 3 characters such as 我想替换前3个字符,例如

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")       

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 Ï : 检查时,如果/是somwere今年前7个字符,并将其替换为Ï

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM