user2150250
user2150250

Reputation: 5157

Replace Character in Matching Regex

I have a substring in a string with the following format:

ID Number: 4D:9B:C4

I am using the following regex to match it:

ID Number: [A-Z0-9]{2}(:[A-Z0-9]{2}){2}

What I want to do is capture instances of substrings matching this regex (or just the first instance), then capture the ID number itself inside, and finally replace colons in the ID Number with spaces, so the output will be:

4D 9B C4

I've been playing around with using capture groups in replace all, surrounding my desired capture in parentheses, like this ....

String idNum = idNum.replaceAll("ID Number: ([A-Z0-9]{2}(:[A-Z0-9]{2}){2})", "$1");

But I'm not sure where to go from here or even if I'm taking the right approach. Any suggestions would be greatly appreciated.

EDIT: Perhaps I didn't phrase this the best way in the description, so I'll illustrate by example. The initial string I'm capturing is a substring within a larger string like ...

We got some text up here
  ID Number: 4D:9B:C4
  And also some text down here

And I want the output previously stated.

Upvotes: 2

Views: 132

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174696

Through regex and regex ony. The anchor \G matches at the position where the previous match ended.

String s = "ID Number: 4D:9B:C4";
System.out.println(s.replaceAll("(?:ID Number: ([A-Z0-9]{2})|(?<!^)\\G):?([A-Z0-9]{2})","$1 $2"));

Output:

4D 9B C4

Another example with many number of colon separated parts.

String s = "ID Number: 4D:9B:C4:B5:C6:D7:F8:K9";
System.out.println(s.replaceAll("(?:ID Number: ([A-Z0-9]{2})|(?<!^)\\G):?([A-Z0-9]{2})","$1 $2"));

Output:

4D 9B C4 B5 C6 D7 F8 K9

References:

Update:

String s = "We got some text up here\n" +
           "ID Number: 4D:9B:C4:D4:F4\n" +
           "And also some text down here";
System.out.println(s.replaceAll("(?s)(?:ID Number: ([A-Z0-9]{2})|(?<!^)\\G):?([A-Z0-9]{2})|.*?(?=ID Number:)|.+","$1 $2").trim());

Upvotes: 3

Robert
Robert

Reputation: 2669

I suggest using capture groups to actually get what you're interested in. There's no reason not to be repetitive.

String idNum = idNum.replaceAll(
   "ID Number: ([A-Z0-9]{2}):([A-Z0-9]{2}):([A-Z0-9]{2})",
   "$1 $2 $3"
);

Upvotes: 1

Andreas Gnyp
Andreas Gnyp

Reputation: 1840

Providing the String schema doesn't change too much, I'd go with

String str = "ID Number: 4D:9B:C4"
numbers = str.split(':')[1].split(':')

Then you might have to .trim() your elements of the array 'numbers'.

After you can go with concatenating numbers[0-2] with spaces inbetween.

Upvotes: 0

fge
fge

Reputation: 121712

You can use a lookahead. And since you will probably use this pattern more than once, create it as a static final variable:

private static final Pattern PATTERN = Pattern.compile(":(?=[A-Z0-9]{2})");

// ...

idNum = PATTERN.matcher(idNum).replaceAll(" ");

Upvotes: 0

Related Questions