【问题标题】:Java String regex replaceJava字符串正则表达式替换
【发布时间】:2015-12-24 17:01:53
【问题描述】:

我的字符串结构如下

字符 1-3 是大写字母,包括 Ň Ö Ï 等变音符号

字符 4-7 始终是数字。

第8个是空格

9th 是正斜杠

第十个空格

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

【问题讨论】:

  • 你能发布一些例子吗?目前还不清楚你想要什么以及你尝试了什么
  • 我不太明白你的问题是什么。
  • 我添加了输入字符串及其预期结果
  • 向我们展示你想要对其进行正则表达式的字符串
  • \p{Lu} 之类的东西可能会帮助您处理大写拉丁字母。见regular-expressions.info/unicode.html

标签: java regex


【解决方案1】:

我想说没有正则表达式会更容易,因为你想替换字符串,但只有当它们位于某些位置时:

检查/是否在前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;

【讨论】:

    猜你喜欢
    • 2014-08-25
    • 2018-07-13
    • 2010-10-04
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多