1

I need to replace each '\w(space)\w' to '\w\w' (without spaces).

Pattern.compile("\\w \\w").matcher("a b c d e f ...").replaceAll("$0")

May I change result in '$0' group (remove spaces) before replacing?

I need to return 'ab cd ef'

More complex example:

123 321 321 ... 123 number -> 123321321...123 number

by regular expression (\d{3} )+(number)

3
  • What are rules of removing or leaving space?
    – Pshemo
    Mar 31, 2015 at 12:33
  • Only spaces between block of numbers are removed.
    – wtrclr
    Mar 31, 2015 at 12:38
  • That doesn't match with your previous requirement where "a b c d e f" should become "ab cd ef".
    – Pshemo
    Mar 31, 2015 at 12:39

2 Answers 2

1

In this simple case each match would have a single space, so removing the space would mean replacing with an empty string. Moreover, String can do it directly, like this:

String res = "a b c d e f ...".replaceAll("\\w \\w", "");

A more interesting case is when you need to process each match as you do replacements. In this case you should use appendReplacement and appendTail methods, which work in tandem:

Pattern p = Pattern.compile("\\w \\w");
Matcher m = p.matcher("a b c d e f ...");
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, "#");
}
m.appendTail(sb);
String result = sb.toString();
1

If you want to perform some operation on the matched result, then you have to use an extra StringBuffer for that, and Matcher.appendReplacement() method.

You can however achieve this without that too:

String result = "a b c d e f".replaceAll("(\\w) (\\w)", "$1$2");
2
  • Your snippet return 'abcdef' but I need 'ab cd ef'
    – wtrclr
    Mar 31, 2015 at 12:02
  • It works, but if i need transform each '123 231 ... 123 number' to 123231...123 number'. I don't know count of groups of three numbers. Expression: (\d{3} )+number
    – wtrclr
    Mar 31, 2015 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.