尚方宝剑之说
在这里试试这个正则表达式: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) 匹配组替换结果。