Piotr
Piotr

Reputation: 694

How to extract string between characters with multiple occurrences regex

As an example I have the line:

if (ProPref.get("kcstcli","manageesw","on").equals("on")) {

I would like to extract:

"kcstcli","manageesw","on"

I tried the non greedy solutions but it doesn't work well ( I am using Groovy ).

it =~ /ProPref.get\((.*)?\)/

Upvotes: 1

Views: 685

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

Non-greedy pattern is .*?, the (.*)? is an optional greedy subpattern that matches 1 or 0 occurrences of 0 or more characters other than a newline.

Use

it =~ /ProPref\.get\((.*?)\)/

Access the captured value via Group 1. See this regex demo

Groovy sample code:

s = "if (ProPref.get(\"kcstcli\",\"manageesw\",\"on\").equals(\"on\")) {"
regex = /ProPref\.get\((.*?)\)/

def m = s =~ regex
(0..<m.count).each { print m[it][1] + '\n' }

Result: "kcstcli","manageesw","on"

Upvotes: 5

Related Questions