你可以尝试这样的事情:
@Test
public void addString() {
String target = "abc,bcd,aefg";
String stringToAdd = "efg";
System.out.println(target);
if(! new HashSet<String>(Arrays.asList(target.split(","))).contains(stringToAdd)) {
target += "," + stringToAdd;
}
System.out.println(target);
if(! new HashSet<String>(Arrays.asList(target.split(","))).contains(stringToAdd)) {
target += "," + stringToAdd;
}
System.out.println(target);
}
输出
abc,bcd,aefg
abc,bcd,aefg,efg
abc,bcd,aefg,efg
代码如下:
- 拆分使用
,
- 通过将数组转换为列表并将其提供给HasSet 的构造函数来生成一组结果数组
- 使用 Set 的方法contains检查要添加的字符串是否存在
- 如果不存在则添加
编辑
您可以尝试使用此正则表达式^efg|^efg,.+|.+,efg,.+|.+,efg$
:
@Test
public void addStringRegEx() {
String target = "abc,bcd,aefg";
String stringToAdd = "efg";
String regex =
// string is alone at first position and there is no comma
"^" + stringToAdd +
"|" + // OR
// string is first and is followed by a comma and some other strings
"^" + stringToAdd + ",.+" +
"|" + // OR
// string is enclosed within two commas i.e. in the middle
".+," + stringToAdd + ",.+" +
"|" + // OR
// string is at the end and there are some strings and comma before it
".+," + stringToAdd + "$";
Assert.assertFalse("aefg".matches(regex));
Assert.assertFalse(",efg".matches(regex));
Assert.assertFalse("efg,".matches(regex));
Assert.assertFalse(",efg,".matches(regex));
Assert.assertTrue("efg".matches(regex));
Assert.assertTrue("foo,efg".matches(regex));
Assert.assertTrue("foo,efg,bar".matches(regex));
Assert.assertTrue("efg,bar".matches(regex));
if(! target.matches(regex)) {
target += "," + stringToAdd;
}
Assert.assertEquals("abc,bcd,aefg,efg", target);
if(! target.matches(regex)) {
target += "," + stringToAdd;
}
Assert.assertEquals("abc,bcd,aefg,efg", target);
}