简体   繁体   English

否定前瞻不符合预期

[英]Negative lookahead doesn't behave as expected

Trying to use regex to parse arguments from a string: "-a 1 -b -5.1" . 试图使用正则表达式来解析字符串中的参数: "-a 1 -b -5.1"

Output should have 2 flags with values: flag a with value 1 , b with -5.1 . 输出应该有2个标志值:标志a值为1b标志值为-5.1

When I try (-(?<flag>[a-zA-Z])(?<value> .+)?(?!-[a-zA-Z]))* regular expression, it returns only flag a with value 1 -b -5.1 . 当我尝试(-(?<flag>[a-zA-Z])(?<value> .+)?(?!-[a-zA-Z]))*正则表达式时,它只返回标志a1 -b -5.1

Why doesn't it stop at -b ? 为什么不在-b停止?

You need to make (?<value> .+) lazy and turn the negative lookahead into a positive lookahead. 你需要使(?<value> .+)懒惰,并将负向前瞻变为积极的前瞻。

Here is my try: 这是我的尝试:

-(?<flag>[a-zA-Z]) (?<value>.+?)(?=$| -[a-zA-Z])

Demo 演示

Explanation: 说明:

You are probably wondering why a positive lookahead is used instead of a negative one. 你可能想知道为什么使用积极的前瞻而不是消极的前瞻。 This is because +? 这是因为+? will stop matching whenever the thing after it matches. 只要匹配后的东西,它就会停止匹配。 This is why we look ahead to find $| -[a-zA-Z] 这就是为什么我们期待找到$| -[a-zA-Z] $| -[a-zA-Z] and if we do find one, +? $| -[a-zA-Z]如果我们找到一个, +? stops matching! 停止匹配!

I have also moved a space character outside of the value group. 我还在value组之外移动了一个空格字符。 I assume you don't want the value to contain spaces? 我假设你不希望值包含空格?

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

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