sunleo
sunleo

Reputation: 10943

String replaceAll multiple characters

Without replaceall Output: [3, 2, 1]

With replaceall Output: 3,2,1

Is there anyway to do this using single replaceAll method, something like

      set.toString().replaceAll("\\[\\]\\s+","");

Now Code

      Set<String> set = new HashSet<String>();    
      set.add("1");
      set.add("2");
      set.add("3");
      System.out.println(set.toString().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s+", ""));

Upvotes: 0

Views: 3449

Answers (3)

Rossiar
Rossiar

Reputation: 2564

replaceAll("[^\\d|,]", ""); will replace everything that is not a digit (\\d) or (|) a comma (,). The hat symbol ^ means not in Java regex and the square brackets [] denote a set. So our set is "everything that is not a digit or a comma".

Set<String> set = new HashSet<String>();
set.add("1");
set.add("2");
set.add("3");
System.out.println(set.toString().replaceAll("[^\\d|,]", ""));

Output:

3,2,1

Upvotes: 0

Rahul
Rahul

Reputation: 45060

How about using this regex, [\\[\\]].

System.out.println(set.toString().replaceAll("[\\[\\]]", "")); // Output is 3,2,1

If you want to remove the white space also, then use this regex, [\\[\\]\\s] (but the comma will be there).

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213223

How about using Guava's Joiner:

String joined = Joiner.on(",").join(set);
System.out.println(joined);  // 1,2,3

Or, if you can't use any 3rd party library, then following replaceAll would work:

System.out.println(set.toString().replaceAll("[\\[\\]]|(?<=,)\\s+", ""));  // 1,2,3

Well, you won't get always the same output, as HashSet doesn't preserve insertion order. If you want that, use LinkedHashSet.

Upvotes: 2

Related Questions