Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all matches of a pattern in a string using regex

Tags:

regex

groovy

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?

like image 780
birdy Avatar asked Aug 28 '14 21:08

birdy


People also ask

How do I return all matches in regex?

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.

Does * match everything in regex?

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.

How do you check if a regex matches a string?

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.


1 Answers

You can use CharSequence.findAll:

def triads = s.findAll("[0-9]{3}")

assert triads == ['234', '433']

Latest documentation of CharSequence.findAll

like image 143
tim_yates Avatar answered Sep 27 '22 20:09

tim_yates