简体   繁体   中英

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

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 [az] will match any lowercase character including vowels this regex will still only match consonants. The (?i) at the beginning make the regex case insensitive.

您可以使用班级交叉点

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM