Matching Strings to Patterns
We can define string patterns, aka "Regular Expressions" or "Regexes", and see if a String matches it:
...
| Code Block |
|---|
def m= ( ~/(a*)|bc/ ).matcher( 'bc' ) //another longhand syntax
m.matches()
assert m.group(1) == null && m.start(1) == -1 && m.end(1) == -1
//if match successful but group didn't match anything
def p= java.util.regex.Pattern.compile( /ab*c/ )
assert p.pattern() == /ab*c/ //retrieve the definition from a compiled pattern
|
Finding Patterns in Strings
As well as matching an entire string to a pattern, we can also find a pattern within a string using =~ syntax:
...
Atomic grouping and possessiveness are handy with nested repetition, allowing much faster match failures.
Finding Positions in Strings
We can use ^ and $ to match the beginning and end of each line using flag m:
...
| Code Block |
|---|
def s= 'hi,my,spy,tie,bye,,'
assert s.split( /,/ ).toList() == ['hi', 'my', 'spy', 'tie', 'bye']
assert s.split( /,/, 1 ).toList() == ['hi,my,spy,tie,bye,,']
//extra argument gives max number of splits
assert s.split( /,/, 2 ).toList() == ['hi', 'my,spy,tie,bye,,']
assert s.split( /,/, 3 ).toList() == ['hi', 'my', 'spy,tie,bye,,']
assert s.split( /,/, 0 ).toList() == ['hi', 'my', 'spy', 'tie', 'bye']
//any number of splits; same as no arg
assert s.split( /,/, -1 ).toList() == ['hi', 'my', 'spy', 'tie', 'bye', '', '']
//a negative arg doesn't remove trailing empty strings
assert ( ~/,/ ).split(s).toList() == ['hi', 'my', 'spy', 'tie', 'bye']
//alternative syntax
assert ( ~/,/ ).split(s, 2).toList() == ['hi', 'my,spy,tie,bye,,']
|
Restricting a String to a Region for a Pattern
We can set the limit of the part of the input string that will be searched to find a match:
...