RegexDemo.java

Download RegexDemo.java

 1: // Demo showing several Java regular expression processing features.
 2: // This code shows using a case-insensitive substring match (using capturing
 3: // groups), then replacing the specific matched group with something.
 4: //
 5: // Written 10/2017 by Wayne Pollock, Tampa Florida USA
 6: 
 7: import java.util.regex.*;
 8: 
 9: class RegexDemo {
10:     public static void main ( String [] args ) {
11:         StringBuilder sb = new StringBuilder( "blah FOO blah" );
12:         Matcher m =
13:         Pattern.compile( "(f(.)\\2)", Pattern.CASE_INSENSITIVE ).matcher( sb );
14:         if ( m.find() ) {  // looking for "foo"
15:            int start = m.start( 1 );
16:            int end = m.end( 1 );
17:            sb.replace(start, end, "BAR");
18:         } else {
19:             System.out.println( "No match!" );
20:         }
21:         System.out.println( sb.toString() );
22:     }
23: }