0

I have two strings :

s = "aaaaaaa" and m = "a"

I want output as commonChars="a" but i am getting commonChars="aaaaaaa" and for s = "a" m = "aaaa"

I want output commonChars="a"

Can anyone suggest me regular expression for that ?

My code is

String commonChars = s.replaceAll("[^" + m + "]", "");
BENARD Patrick
  • 30,363
  • 16
  • 99
  • 105
Jayesh Ahir
  • 51
  • 1
  • 9

1 Answers1

1

You could do

String commonChars = s.replaceAll(m + "+", m);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Thank you..but what if i also want to find the common character in two string like if s = "avfd" m = "av" than output is commonChars="av" – Jayesh Ahir Feb 10 '14 at 13:38
  • @JayeshAhir It depends on how you use it. :) – Prasad Feb 10 '14 at 13:40
  • Basicly i want find common characters in two string ..so can you suggest me regex for that..thanks – Jayesh Ahir Feb 10 '14 at 13:42
  • You can't use regular expressions that way. A regular expression is a single expression which matches a number of strings. It can't be used to extract common characters of multiple strings. – tilois Feb 10 '14 at 13:42
  • Indeed see [this post](http://stackoverflow.com/questions/4203911/how-do-i-find-the-characters-common-to-two-strings-in-java-using-single-replacea) to see how problematic that can be – Reimeus Feb 10 '14 at 13:45
  • same code i am using for finding common characters but i also want answer that gives me output specified in my question . – Jayesh Ahir Feb 10 '14 at 13:47