2 回答

TA贡献1788条经验 获得超4个赞
在这里试试这个正则表达式:
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) 将包含您的“Sample Country”字符串,我们可以只用第一个 ($1) 和第三个 ($3) 匹配组替换结果。

TA贡献1827条经验 获得超9个赞
编辑 :
让我们做一个更好的方法。您将不仅有 2 个案例 您将有 3 个案例
(模式+数据) ---> ^Sample[^!]+! (模式) ([^!]) (数据)
(数据+模式) --->([^!])(数据) 样本[^!]+!$ (模式)
(模式 + 数据 + 模式) ---> (^Sample[^!]+! (模式) ([^!]) (数据) Sample[^!]+!$ (模式)
所以我们必须用正则表达式检查字符串中的所有情况。我们需要正则表达式中的 OR 案例,它是“|” 另一件事是我们必须避免不匹配的情况必须被忽略,这里描述的是 (?:(regex))
public class HelloWorld {
public static void main(String[] args) {
String[] testcases = new String[] {
"Sample foo ! Test1 Data",
"Sample bar ! Test2 Data",
"Test3 Data Sample foo !",
"Test4 Data Sample bar !",
"Sample bar ! Test5 Data Sample bar !"
};
for (String str: testcases) {
System.out.println(str.replaceAll("(?:(^Sample[^!]+!([^!])))|(?:(([^!])Sample[^!]+!$))|(?:(^Sample[^!]+!([^!]))Sample[^!]+!$)", "$2$4").trim());
}
}
我们使用您的正则表达式并在分组数据后创建一个新的正则表达式将位于 ($2,$4) 组,因为我们将字符串替换为第 2 组和第 4 组值。我希望这将有所帮助。
添加回答
举报