Search code examples
javaregexgroovy

Groovy/Java: match command option with quoted value


I try to match if a command string contains a quoted value as one of its option. Below is what I have gotten so far:

def pattern = ~/\s+[-]{1,2}\w\s+'.*'/

assert "cmd -o '{}'" =~ pattern
assert 'cmd -o \'{"a": "b"}\'' =~ pattern
assert 'cmd --option \'{"a": "b"}\'' =~ pattern // failed
assert 'cmd --long-option \'{"a": "b"}\'' =~ pattern // failed

Any suggestion how to make long option works?


Solution

  • You may use this regex to match all the cases provided in your question:

    \s+-{1,2}\w[\w-]*\s+'[^']*'
    

    RegEx Demo

    RegEx Details:

    • \s+: Match 1+ whitespace
    • -{1,2}: Match 1 or 2 hyphens
    • \w[\w-]*: Match 1+ of word or hyphen characters starting with a word character
    • \s+: Match 1+ whitespace
    • '[^']*': Match a string wrapped in single quotes