如何删除字符串中除“ 1”和“ 2”以外的所有数字?

时间:2019-10-02 17:48:19

标签: java regex string

我想删除String中所有独立的数字12中的所有数字。然后我想将1替换为one,将2替换为two

例如,我期望的输入和输出如下:

String myString = "Happy New Year 2019, it's 1 January now,2 January tommorow";

预期输出:

myString = "Happy New Year, it's one January now,two January tommorow";

因此,1中的22019被删除,但单独的12one和{ {1}}。

我尝试使用正则表达式,但是所有数字均被删除。这是我的代码:

two

我还尝试用此正则表达式public String cleanNumber(String myString){ String myPatternEnd = "([0-9]+)(\\s|$)"; String myPatternBegin = "(^|\\s)([0-9]+)"; myString = myString.replaceAll(myPatternBegin, ""); myString = myString.replaceAll(myPatternEnd, ""); return myString; } [1]代替,但是[2]变成2019

我不知道如何更改单独的two0one91。有什么建议吗?

3 个答案:

答案 0 :(得分:3)

您可以按以下顺序使用replaceAll

myString = myString
          .replaceAll("\\b1\\b", "one") // replace 1 by one
          .replaceAll("\\b2\\b", "two") // replace 2 by two
          .replaceAll("\\s*\\d+", "");  // remove all digits

//=> Happy New Year, it's one January now,two January tommorow

在替换12时使用单词边界很重要,以避免将这些数字作为其他数字的一部分进行匹配。

答案 1 :(得分:1)

您可以致电String#replaceAll,在其中,正则表达式模式在12的任一侧查找数字:

public String cleanNumber(String myString) {
    return myString.replaceAll("(?<!\\d)1(?!\\d)", "one")
                   .replaceAll("(?<!\\d)2(?!\\d)", "two");
}

输出:

Happy New Year 2019, it's one January now,two January tommorow

灵感来自:Java Regex to replace string surrounded by non alphanumeric characters

答案 2 :(得分:0)

首先替换一个数字1和2,然后删除所有其他数字

public String cleanNumber( String s ){
  s = s.replaceAll( "(\\D)1(\\D)", "$1one$2" ).replaceAll( "(\\D)2(\\D)", "$1two$2" );
  return( deleteChars.apply( s, "0123456789" ) );
}

String myString = "Happy New Year 2019, it's 1 January now,2 January tommorow";
cleanNumber( myString );  // Happy New Year , it's one January now,two January tommorow

find deleteChars here