Groovy regex PatternSyntaxException when parsing GString-style variables -
groovy here. i'm being given string gstring-style variables in like:
string target = 'how brown ${animal}. ${role} has oddly-shaped ${bodypart}.' keep in mind, not intended used actual gstring!!! is, i'm not going have 3 string variables (animal, role , bodypart, respectively) groovy resolving @ runtime. instead, i'm looking 2 distinct things these "target" strings:
- i want able find instances of these variables refs (
"${*}") in target string, , replace?; and - i need find instances of these variables refs , obtain list (allowing dupes) names (which in above example,
[animal,role,bodypart])
my best attempt far:
class targetstringutils { private static final string variable_pattern = "\${*}" // example input: 'how brown ${animal}. ${role} has oddly-shaped ${bodypart}.' // example desired output: 'how brown ?. ? has oddly-shaped ?.' static string replacevarswithquestionmarks(string target) { target.replaceall(variable_pattern, '?') } // example input: 'how brown ${animal}. ${role} has oddly-shaped ${bodypart}.' // example desired output: [animal,role,bodypart] } list of strings static list<string> collectvariablerefs(string target) { target.findall(variable_pattern) } } ...produces patternsytaxexception anytime go run either method:
exception in thread "main" java.util.regex.patternsyntaxexception: illegal repetition near index 0 ${*} ^ any ideas i'm going awry?
the issue have not escaped pattern properly, , findall collect matches, while need capture subpattern inside {}.
use
def target = 'how brown ${animal}. ${role} has oddly-shaped ${bodypart}.' println target.replaceall(/\$\{([^{}]*)\}/, '?') // => how brown ?. ? has oddly-shaped ?. def lst = new arraylist<>(); def m = target =~ /\$\{([^{}]*)\}/ (0..<m.count).each { lst.add(m[it][1]) } println lst // => [animal, role, bodypart] see this groovy demo
inside /\$\{([^{}]*)\}/ slashy string, can use single backslashes escape special regex metacharacters, , whole regex pattern looks cleaner.
\$- match literal$\{- match literal{([^{}]*)- group 1 capturing characters other{,}, 0 or more times\}- literal}.
Comments
Post a Comment