gpt4 book ai didi

Java Regex - 如何替换以以下开头和结尾的模式

转载 作者:太空宇宙 更新时间:2023-11-04 09:55:08 24 4
gpt4 key购买 nike

我有两种情况:

  1. 字符串以示例国家/地区开头!即样本国家!测试数据

我想要一个正则表达式来替换示例国家/地区!对于空字符串,这里的国家不固定,可以是美国、法国等

我尝试过:

System.out.println(str.replaceAll("^(Sample[^!]+!)", ""));

我正在获取输出

! Test Data 

而我只是想要

Test Data
  • 字符串以示例国家/地区结尾!即测试数据样本国家/地区!我也只想在这里

    测试数据

  • 有人可以帮忙提供正确的正则表达式和解释吗?非常感谢

    最佳答案

    在这里尝试这个正则表达式:

    String[] testcases = new String[] {
    "Sample foo ! Test Data",
    "Sample bar ! Test Data",
    "Test Data Sample foo !",
    "Test Data Sample bar !"
    };

    for (String str : testcases) {
    System.out.println(str.replaceAll("(.* ?)(Sample[a-zA-Z ]+ ! ?)(.*)", "$1$3"));
    }

    说明:

    (.* ?) // first match group, matches anything, followed by an optional space

    (Sample[a-zA-Z ]+ ! ?) // second match group, matches the String "Sample followed by a series of letters (your country), a whitespace, an exclamation mark and an optional space

    (.*) // third match group, matches anything

    因此,第二个匹配组 ($2) 将包含您的“示例国家/地区”字符串,我们只需将结果替换为第一个 ($1) 和第三个 ($3) 匹配组。

    关于Java Regex - 如何替换以以下开头和结尾的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245910/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com