あなたはそのようなことを試すことができます:
@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);
}