0

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+", ""));
0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I knew it Jain thing want for is how to replace multiple regex with single replace all method, GOT IT .Thank you.
@sunleo. You can always merge multiple regex using alternation - |.
1

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).

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.