Java RegEx

Here's some code to get started with Java regular expression (RegEx) quickly...

// Import usefull stuff (needed for option 2)
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Indexer {
 
 public static void main(String[] args) {
  
  // This is the pattern we are going to use: [A-Z]*\\s?(\\d+)
  // 
  // Explained:
  //  First note: \\ is used to generate one '\' (escaping) 
  //   [A-Z] any capital letter
  //   * (0 or more times)
  //   \s white space (ie tab, space)
  //   ? (0 or 1 time)
  //   \d numerical digit
  //   + one or more times
  //   Note: (/d+) means: capture this part separately

  // Option 1: Going right in
  if (   "ABC123".matches( "[A-Z]*\\s?(\\d+)" ) ) 
   System.out.println( "'ABC123' matches!" ); 
  if (   "ABC 123".matches( "[A-Z]*\\s?(\\d+)" ) ) 
   System.out.println( "'ABC 123' matches as well!" );
  if ( ! "ABC  123".matches( "[A-Z]*\\s?(\\d+)" ) ) 
   System.out.println( "'ABC  123' doesn't!" );
  if ( ! "ABC 123X".matches( "[A-Z]*\\s?(\\d+)" ) ) 
   System.out.println( "'ABC 123X' doesn't!" );

  // Option 2: faster and more versatile

  // Pre-compile the regular expression pattern
  Pattern myPattern = Pattern.compile( "[A-Z]*\\s?(\\d+)" );
  
  // Match it
  Matcher myMatcher = myPattern.matcher( "ABC123" );
  if ( myMatcher.find() ) System.out.println( "Match!" );

  // Get the parts out that you want, note: it's a String!
  String number = myMatcher.group( 1 );
  
  // Use it as a string
  System.out.println( "Captured: " + number );
  
  // Or parse it to integer
  int i = Integer.parseInt( myMatcher.group(1) );
  System.out.println("Parsed to int and added one: " + ( i + 1 ));
  
 }
 
}

Geen opmerkingen:

Een reactie posten