Java Reference
In-Depth Information
Smith, John
Adams, John Quincy
and you want to get out:
John Smith
John Quincy Adams
just use:
public
public class
class REmatchTwoFields
REmatchTwoFields {
public
public static
void main ( String [] args ) {
String inputLine = "Adams, John Quincy" ;
// Construct an RE with parens to "grab" both field1 and field2
Pattern r = Pattern . compile ( "(.*), (.*)" );
Matcher m = r . matcher ( inputLine );
iif (! m . matches ())
throw
static void
new IllegalArgumentException ( "Bad input" );
System . out . println ( m . group ( 2 ) + ' ' + m . group ( 1 ));
throw new
}
}
Replacing the Matched Text
As we saw in the previous recipe, regex patterns involving quantifiers can match a lot of
characters with very few metacharacters. We need a way to replace the text that the regex
matched without changing other text before or after it. We could do this manually using the
String method substring() . However, because it's such a common requirement, the Java
Regular Expression API provides some substitution methods. In all these methods, you pass
in the replacement text or “righthand side” of the substitution (this term is historical: in a
command-line text editor's substitute command, the lefthand side is the pattern and the
righthand side is the replacement text). The replacement methods are:
replaceAll(newString)
Replaces all occurrences that matched with the new string.
appendReplacement(StringBuffer, newString)
Copies up to before the first match, plus the given newString .
Search WWH ::




Custom Search