Regex in Java

Methods

#Pattern

  • Pattern compile(String regex [, int flags])
  • boolean matches([String regex, ] CharSequence input)
  • String[] split(String regex [, int limit])
  • String quote(String s)

#Matcher

  • int start([int group | String name])
  • int end([int group | String name])
  • boolean find([int start])
  • String group([int group | String name])
  • Matcher reset()

#String

  • boolean matches(String regex)
  • String replaceAll(String regex, String replacement)
  • String[] split(String regex[, int limit]) There are more methods …

Pattern Fields

- -
CANON_EQ Canonical equivalence
CASE_INSENSITIVE Case-insensitive matching
COMMENTS Permits whitespace and comments
DOTALL Dotall mode
MULTILINE Multiline mode
UNICODE_CASE Unicode-aware case folding
UNIX_LINES Unix lines mode

Styles

#First way

Pattern p = Pattern.compile(".s", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("aS");  
boolean s1 = m.matches();  
System.out.println(s1);   // Outputs: true

#Second way

boolean s2 = Pattern.compile("[0-9]+").matcher("123").matches();  
System.out.println(s2);   // Outputs: true

#Third way

boolean s3 = Pattern.matches(".s", "XXXX");  
System.out.println(s3);   // Outputs: false
Comments