I have a String
that looks like "(doc1| doc1| provid| geestt| stable)"
. It represents an array and I want to remove any duplicates from it so that doc1 appears only once. How can I do this?
Asked
Active
Viewed 250 times
0

Jaydee
- 4,138
- 1
- 19
- 20

user3772927
- 27
- 6
-
In your title you mention that your array is seperated by "|" - do you have a String or an array? Because an array doe snot have a seperation sign – LionC Aug 14 '14 at 10:24
-
1"How can I do this?" By coding. – Mena Aug 14 '14 at 10:26
-
It's a string and the results are separated by a delimiter, i had found something like this below but it's not working, i tried to change but it doesnt work` var uniqueArray = duplicatesArray.filter(function(elem, pos) { return duplicatesArray.indexOf(elem) == pos; }); ` – user3772927 Aug 14 '14 at 10:28
-
possible duplicate of [How to get an array of unique values from an array containing duplicates in JavaScript?](http://stackoverflow.com/questions/13486479/how-to-get-an-array-of-unique-values-from-an-array-containing-duplicates-in-java) – Michael Sanchez Aug 14 '14 at 10:31
-
thank you @ Michael i will look at those. – user3772927 Aug 14 '14 at 10:36
-
It's not a duplicate, as the above link asks for a Java solution, not Javascript. I'd rather look at `String.split()` [http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String] and `java.util.Set` [http://docs.oracle.com/javase/7/docs/api/java/util/Set.html] – david a. Aug 14 '14 at 11:04
1 Answers
0
String s = "(doc1|doc1|provid|geestt|provid|stable)";
s = s.replaceAll("\\b(\\w+)\\|(?=.*\\b\\1\\b)", "");
System.out.println(s);
// (doc1|geestt|provid|stable)
This uses \\w
for word char; probably you need [^|)]
that is: not one of the separator chars. The 0-char wide \\b
is for detecting word boundaries, that fits.
This pattern uses a look-ahead (?= ... )
containing \\1
the 1st matched ()
group: the word.
P.S.
Set<String>
seems to be a more appropiate data structure.

Joop Eggen
- 107,315
- 7
- 83
- 138