If I have a string like:
s = "This is a simple string 234 something else here as well 4334
and a regular expression like:
regex = ~"[0-9]{3}"
How can I extract all the words from the string using that regex? In this case 234
and 433
?
The method str. match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details.
Throw in an * (asterisk), and it will match everything. Read more. \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character.
If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.
You can use CharSequence.findAll
:
def triads = s.findAll("[0-9]{3}")
assert triads == ['234', '433']
Latest documentation of CharSequence.findAll
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With