【问题标题】:Replace blank spaces and semicolon in Java with Regex [duplicate]用正则表达式替换Java中的空格和分号[重复]
【发布时间】:2019-02-15 21:25:49
【问题描述】:

我正在尝试将所有可以包含任意数量空格后跟结尾“;”的字符串替换为“;”但我很困惑,因为有多个空格。

"ExampleString1            ;" -> "ExampleString1;"
"ExampleString2  ;" -> "ExampleString2;"
"ExampleString3     ;" -> "ExampleString3;"
"ExampleString1 ; ExampleString1 ;" -----> ExampleString1;ExampleString1

我试过这样:example.replaceAll("\\s+",";") 但问题是可能有多个空格,这让我很困惑

【问题讨论】:

  • @Eugene 他想要一个分号,而不是删除整个东西。
  • @AlexShesterov 纠正了...作为答案,感谢您发现这一点,并且 OP 显示他尝试了一些 btw...

标签: java regex


【解决方案1】:

试试这个:

replaceAll("\\s+;", ";").replaceAll(";\\s+", ";")

【讨论】:

    【解决方案2】:

    基本上做一个匹配先找到

    (.+?) ->  anything in a non-greedy fashion
    (\\s+) -> followed by any number of whitespaces
    (;) -> followed by a ";"
    $ -> end of the string
    

    而不是简单地删除第二组(空格),只需通过$1$3获取第一组和第三组

    String test = "ExampleString1            ;"; 
    test = test.replaceFirst("(.+?)(\\s+)(;)$", "$1$3");
    System.out.println(test); // ExampleString1;
    

    【讨论】:

    • 如果您只希望每个字符串有一个匹配项,为什么要使用replaceAllreplaceFirst 就够了。
    • @WiktorStribiżew 好点,已编辑
    • 如果字符串是这样的:"ExampleString1 ; ExampleString1 ;"
    • @xmlParser 预期的结果是什么?
    • @Eugene "ExampleString1 ; ExampleString1 ;" -----> ExampleString1;ExampleString1;
    【解决方案3】:

    你只需要像这样转义元字符\s

    "ExampleString1   ;".replaceAll("\\s+;$", ";")
    

    【讨论】:

    • 如果您只希望每个字符串有一个匹配项,为什么要使用.replaceAllreplaceFirst 就够了。
    • 如果字符串是这样的:"ExampleString1 ; ExampleString1 ;"
    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    相关资源
    最近更新 更多