Search code examples
regexgroovymatching

Groovy Regex multiple matches


With the following string saved in variable "start":

user stuff here 5
user banana1 pswd 4 
user lemon2 pswd 5
mumbo jumbo 12333 3
user h3lp pswd 8

What regex will grab the three digits(4,5,8) after 'pswd' preceded by a random string and 'user'? New to groovy matching. I attempted this (username.*secret).\d

would ideally like to perform something like this, where the matches can then be accessed in an array

def pattern = ~/\S+er\b/
def matcher = "My code is groovier and better when I use Groovy there" =~ pattern
assert matcher[0..-1] == ["groovier", "better"]

Solution

  • You can use

    /\buser\s+\S+\s+pswd\s+(\d+)/
    

    See the regex demo. Details:

    • \b - a word boundary
    • user - a user word
    • \s+ - one or more whitespaces
    • \S+ - one or more non-whitespaces (some word)
    • \s+ - one or more whitespaces
    • pswd - a pswd word
    • \s+ - one or more whitespaces
    • (\d+) - Group 1: one or more digits.

    See the Groovy demo:

    String s = "user stuff here 5\nuser banana1 pswd 4\nuser lemon2 pswd 5\nmumbo jumbo 12333 3\nuser h3lp pswd 8"
    def re = /\buser\s+\S+\s+pswd\s+(\d+)/
    def res = (s =~ re).collect { it[1] }
    print(res)
    

    Output:

    [4, 5, 8]