Pattern methods
A regex is useless until code compiles that string into a
Pattern
object. Accomplish that task with either of the following compilation methods:
- public static Pattern compile(String regex)
:
compiles regex
's contents into a tree-structured object representation stored in a new Pattern
object. A reference to that object returns. Example: Pattern p = Pattern.compile ("(?m)^\\.");
creates a Pattern
object that stores a compiled representation of the regex for matching all lines starting with a period character.
- public static Pattern compile(String regex, int flags)
:
accomplishes the same task as the previous method. However, it also considers a bitwise inclusive ORed set of flag constant bit values (which flags
specifies). Flag constants are declared in Pattern
and serve (except the canonical equivalence flag, CANON_EQ
) as an alternative to embedded flag expressions. Example: Pattern p = Pattern.compile ("^\\.", Pattern.MULTILINE);
is equivalent to the previous example, where the Pattern.MULTILINE
constant and the (?m)
embedded flag expression accomplish the same task. (Consult the SDK's Pattern
documentation to learn about other constants.) This method throws an IllegalArgumentException
object if bit values other than those bit values that Pattern
's constants represent appear in flags
.
When needed, obtain a copy of a
Pattern
object's flags and the original regex that compiled into that object by calling the following methods:
- public int flags()
:
returns the Pattern
object's flags specified when a regex compiles. Example: System.out.println (p.flags ());
outputs the flags associated with the Pattern
object that p
references.
- public String pattern()
:
returns the original regex that compiled into the Pattern
object. Example: System.out.println (p.pattern ());
outputs the regex corresponding to the Pattern
that p
references. (The Matcher
class includes a similar Pattern pattern()
method that returns a matcher's associated Pattern
object.)
No comments:
Post a Comment