我有一个输入字符串,如:
-a var1=Bat"m/an -b var2=" -a="lol " -c var3=" M^a%g-i=c "
分裂之后,我应该得到:
输出
- -a
- var1=Bat"m/an
- -b
- var2=" -a="lol "
- -c
- var3=" M^a%g-i=c "
规则:
-(char)(atleast one space)variable=value
Bat"m/an
" -a="lol "
或" M^a%g-i=c "
我写了正则表达式,但引号内的引号搞砸了它:
(?:"[^"]*"|\S)+
此外,我尝试在="
上解析字符明智或分裂,但我也面临歧义,因为它们也可以在引号内。
答案 0 :(得分:2)
您可以将此正则表达式用于匹配与前瞻断言:
-?[a-z_]\w*(?:=".*?"(?=\h+(?:-[a-z](?=\h|$)|[a-z]\w*=)|$)|\S+)?
RegEx说明:
-?
:以可选的连字符[a-z_]\w*
:匹配以小写字母或下划线开头,后跟0 +字符开头的变量(?:
:启动非捕获组
".*?"(?=...<expression>)
:匹配以双引号开头和结尾的引用字符串。使用前瞻我们断言我们有另一个变量或前面的行尾。|
:或\S+
:匹配1个非空格字符)
:结束非捕获组答案 1 :(得分:0)
您可以尝试以下内容:
(-[a-z]|[^\s][^\s]*="?[^"]*"?[^\s]*)
其中所有参数及其值将作为单独的组捕获
说明:
Capturing Group (-[a-z]|[^\s][^\s]*="?[^"]*"?[^\s]*)
1st Alternative -[a-z]
2nd Alternative [^\s][^\s]*="?[^"]*"?[^\s]*
[^\s] - A character which should not be a space
[^\s]* - Matches all non space characters
= checks for equal to as mandatory
= matches the character = literally (case sensitive)
"? checks if " symbol is there
[^"]* checks for all symbols that are not as "
"? Again check for " as option
[^\s]* Finally again check for all non space characters
希望有帮助:)。