Tuesday, November 24, 2009

Using regular expressions in Java

Below is an example of using Java's regular expression functionality to replace the spaces inside of a parenthesis with a underscore:

String inputStr = "1 (2 3) 4 (5 6) 7 8 9";
String thePatternStr = "\\([\\w\\d\\s]*\\)";
Pattern pattern = Pattern.compile(thePatternStr);
Matcher matcher = pattern.matcher(inputStr);
StringBuffer sb = new StringBuffer();
while(matcher.find())
{
String match = matcher.group();
String matchWithUnderscore = match.replace(' ', '_');
matcher.appendReplacement(sb, matchWithUnderscore);
}
matcher.appendTail(sb);
System.out.println("Input string: " + inputStr);
System.out.println("Modified string: " + sb.toString());

This should give the following output:

Input string: 1 (2 3) 4 (5 6) 7 8 9
Modified string: 1 (2_3) 4 (5_6) 7 8 9

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home