Skip to main content

RFE: New method(s) for regex based replacement

1 reply [Last post]
yogendrarampuria
Offline
Joined: 2006-12-10
Points: 0

Hi,
In the Matcher class, there are methods for replacing the matched region
* replaceAll(String replacement)
* replaceFirst(String replacement)
* appendReplacement(StringBuffer buffer, String replacement)

I would like to suggest for method or may be redefining the existing methods to incorporate format based string. Although, the replacement argument in the can take the reference to the matching groups, but it does not allow the matched string to be manipulated/formatted.

Allowing for format specifier will actually help in reducing several loops and faster applications. For example see the scenario below.

Before:
String data = "apple 1,grape 2, banana 3, mango 4, foo 5,bar 6, foobar 7, food 8, drink 9,cloths 10, car 11";
Matcher m = Pattern.compile("([a-z]+)\\s+(\\d+),?").matcher(data);
StringBuffer b = new StringBuffer();
while(m.find()){
b.appendReplacement(b,String.format("%1$02d %2$S",m.group(1),m.group(2)));
}
b.appendTail();

After

Matcher m = Pattern.compile("([a-z]+)\\s+(\\d+),?").matcher(data);
StringBuffer b = new StringBuffer();
while(m.find()){
b.appendReplacementFormat(b,"%1$02d %2$S");
}
b.appendTail();

The argument index can be considered as group index and the substitution can be carried out.

Please post your queries and suggestions.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
cowwoc
Offline
Joined: 2003-08-24
Points: 0

I'm not a fan of the readability of regular expressions in general but your proposal seems to make it even worse and opens the door further to typos that will only get caught at runtime.