In java, which regular expression can be used to replace these, for example:
before: aaabbb after: ab
before: 14442345 after: 142345
thanks!
The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
You can try a regular expression like (.)\ 1+ , i.e. "something, then more of the same something", and replace it with \1 , i.e. "that first something". >>> import re >>> re.
*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string.
In perl
s/(.)\1+/$1/g;
Does the trick, I assume if java has perl compatible regexps it should work too.
Edit: Here is what it means
s { (.) # match any charater ( and capture it ) \1 # if it is followed by itself + # One or more times }{$1}gx; # And replace the whole things by the first captured character (with g modifier to replace all occurences)
Edit: As others have pointed out, the syntax in Java would become
original.replaceAll("(.)\\1+", "$1");
remember to escape the \1
String a = "aaabbb"; String b = a.replaceAll("(.)\\1+", "$1"); System.out.println("'" + a + "' -> '" + b + "'");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With