Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a character to regex

Tags:

java

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

like image 946
Mintz Avatar asked Nov 26 '25 16:11

Mintz


1 Answers

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.

like image 59
Andrew Clark Avatar answered Nov 28 '25 05:11

Andrew Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!