简体   繁体   English

为简单的选项解析器在 Java 正则表达式中查找多个组

[英]Finding multiple groups in Java regex for simple option parser

I need to modify this regex to find multiple group matches:我需要修改这个正则表达式来查找多个组匹配:

(?:--)(?<key>[^\\s=]+)(?:(?<assign> *[ =] *)(?! --)(?<value>"[^"]*"|\\S+))?

In Java:在 Java 中:

"(?:--)(?<key>[^\\\\s=]+)(?:(?<assign> *[ =] *)(?! --)(?<value>\\"[^\\"]*\\"|\\\\S+))?"

This matches the following correctly:这正确匹配以下内容:

  • --key=value
  • --key=--value
  • --key value
  • --flag
  • --key="--value"
  • --key "--value"
  • --key=value --foo=bar
  • --key=value --foo=bar --flag

But it fails if --flag comes before any other options:但是如果--flag出现在任何其他选项之前,它就会失败:

  • --key=value --flag --foo=bar

I've been trying to modify the negative lookahead between the assign and value capture groups without success so far.到目前为止,我一直在尝试修改assignvalue捕获组之间的负前瞻,但没有成功。 The value captured for flag ends up being --foo=bar instead of null .flag捕获的value最终是--foo=bar而不是null

Any expert recommendations on how to solve this?有关如何解决此问题的任何专家建议?

I managed to fix the regex.我设法修复了正则表达式。 The website https://regexr.com/ was invaluable.网站https://regexr.com/非常宝贵。

The fixed regex is:固定的正则表达式是:

(?<prefix>--)(?<key>[^\\s=]+)(?:(?! --)(?<assign> *[ =] *)(?! --)(?<value>"[^"]*"|\\S+))?

Here's the Java class and unit test:这是 Java 类和单元测试:

https://gist.github.com/kirklund/845baf340a1999a57db9e59e6ba40ce0 https://gist.github.com/kirklund/845baf340a1999a57db9e59e6ba40ce0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM