How to find all pattern matches in a string using regex

If I have a line like:

s = "This is a simple string 234 something else here as well 4334 

and a regular expression like:

 regex = ~"[0-9]{3}" 

How to extract all words from a string using this regular expression? In this case, 234 and 433 ?

+7
regex groovy
source share
3 answers

Short make

 def triads = s.findAll("[0-9]{3}") assert triads == ['234', '433'] 
+9
source share

You can do something like this.

 def s = "This is a simple string 234 something else here as well 4334" def m = s =~ /[0-9]{3}/ (0..<m.count).each { print m[it] + '\n' } 

Exit ( Work Demo )

 234 433 
+4
source share

You must use capture groups. You can check groovy documentation about it:

http://groovy.codehaus.org/Tutorial+5+-+Capturing+regex+groups

For example, you can use this code:

 s = "This is a simple string 234 something else here as well 4334" regex = /([0-9]{3})/ matcher = ( s=~ regex ) if (matcher.matches()) { println(matcher.getCount()+ " occurrence of the regular expression was found in the string."); println(matcher[0][1] + " found!") } 

As a note:

 m[0] is the first match object. m[0][0] is everything that matched in this match. m[0][1] is the first capture in this match. m[0][n] is the n capture in this match. 
+3
source share

All Articles