Mintz
Mintz

Reputation: 969

Match a character to regex

I want to duplicate all consonants characters in a String. As an example:

Hello, how do you do?

would become:

HHellllo, hhoww ddo yyouu ddo?

So far here's what I've came up with.

char[] charArray = "Hello, how do you do?".toCharArray();
String pattern = "[BbCcDdFfGgHhJjKkLlMmNnPpQqRrSsTtVvWwXxZz]";
StringBuffer sb = new StringBuffer();

for(char c : charArray){
   String theChar = "" + c;
   if(theChar.matches(pattern)){
       sb.append(c);
   }
   sb.append(c);
}

System.out.println(sb.toString());

It works but I'm sure there's a better way to use regex for this. I just don't feel that it's efficient to create a String for each character each time I need to use matches().

Upvotes: 2

Views: 469

Answers (3)

Andrew Clark
Andrew Clark

Reputation: 208405

You can use String.replaceAll with your current regex and "$0$0" as the replacement, to duplicate all of the matches (each match will be a single character):

String text = "Hello, how do you do?";
String pattern = "[BbCcDdFfGgHhJjKkLlMmNnPpQqRrSsTtVvWwXxZz]";
String result = text.replaceAll(pattern, "$0$0");
System.out.println(result);

In the replacement string $0 is a reference to the entire match, if you have capturing groups you can use $1, $2, and so on to refer to the associated capturing group. The following page has some additional info on using regular expressions in Java:
http://www.regular-expressions.info/java.html

Note that you can also shorten your regex a bit, Casimir's answer has a nice approach, here is another:

String pattern = "(?i)(?![aeiou])[a-z]";

This works because (?![aeiou]) is a negative lookahead that means "fail if the next character is a vowel", so even though [a-z] will match any lowercase character including vowels this regex will still only match consonants. The (?i) at the beginning make the regex case insensitive.

Upvotes: 4

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can use a class intersection

String result = text.replaceAll("(?i)[b-z&&[^eiouy]]" , "$0$0");

Upvotes: 4

heptadecagram
heptadecagram

Reputation: 898

String class has a builtin method, replaceAll(), for just such an occasion.

String sb = input.replaceAll("([BbCcDd...])", "$1$1");

The $1 means "whatever was in the parentheses in the pattern".

Upvotes: 1

Related Questions