Jono
Jono

Reputation: 18108

java regex search and replace all?

I have an example input that can be of any length and want to add a space every 4 characters.

for example input = xxxxxxxxxxxx

result I expect: xxxx xxxx xxxx

I have looked at the replaceAll() method but wondering how I can create a match that returns me the 4th, 8th, 12th etc character index so I can do something like this:

input.replaceAll("([\\S\\s)]{4})\\G", " " + input.charAt(index - 1))

where index somehow gets modified to get the appropriate index in which the regular expression of mine has found the 4th character.

Upvotes: 2

Views: 168

Answers (5)

54l3d
54l3d

Reputation: 3973

This will not add a space if there is one

String s = "xxxxxxxx xxxxx x xx x";
System.out.println(s.replaceAll("\\w{4}(?!\\s)", "$0 " ));

Outmput: xxxx xxxx xxxx x x xx x

demo

Upvotes: 0

Pshemo
Pshemo

Reputation: 124215

You can try with replaceAll(".{1,4}+(?!$)", "$0 ")

  • .{1,4}+ will match any 1-4 characters (+ will make it possessive)
  • (?!$) which are not right before end of string

  • $0 " will replace it with content from group 0 (which is current match) plus space


Actually I overcomplicated this regex. You can find simpler version based on same idea in @Kent's answer.

Upvotes: 2

Kent
Kent

Reputation: 195029

"xxxxxxxxxxxx".replaceAll(".{4}(?!$)","$0 ");

This won't add trailing space to the last segment.

Upvotes: 4

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

You can try this wihout using regex:

StringBuilder str = new StringBuilder("xxxxxxxxxxxx");
int i = str.length() - 4;

while (i > 0)
{
    str.insert(i, " ");
    i = i - 4;
}

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

With regex:

String myString = "xxxxxxxxxxxx";
String str = myString.replaceAll("(.{4})(?!$)", "$0 ");
return str;

Upvotes: 2

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Use grouping; $1 (and upwards) will get replaced with matcher.getGroup(1) .

Upvotes: 0

Related Questions