dongmen9517
2018-04-04 20:26
浏览 112
已采纳

解析参数列表中用逗号分隔的逗号分隔值

So i have this regex:

=([0-9A-Za-z_-]+),?

and i need have a string like:

foo=bar,pine=apple,tree,bar=bie
or
foo=bar,pine=apple,tree
or 
pine=apple,tree

the regex works for cases where i only have 1 value. but since we have comma's in the list of values for the key. the regex just craps out and my code does half of what i want it to do but doesn't get the 2nd value.

How do i fix my regex to take both values regardless of where in the string it is? alone, between 2 others, at the end.

i tried some stuff but couldn't figure it out.

Attempt 1:

=([0-9A-Za-z,_-]+),=?

In this case, it matches the one where it's in the middle but it fails on the others because = does not exist.

Attempt 2:

=[0-9A-Za-z_-]+([,]+[0-9A-Za-z_-]*),?

Matches too bar,pine and tree,bar for example

EDIT::

This seems to work maybe....

=('[0-9A-Za-z,_-]+'),*|=([0-9A-Za-z_-]+),*

if i use quotes for multi values..

图片转代码服务由CSDN问答提供 功能建议

所以我有这个正则表达式:

  =([0  -9A-Za-z _-] +),?
   
 
 

,我需要输入类似以下字符串:

  foo = bar,pine = apple,tree,bar = bie 
or 
foo = bar,pine = apple,tree 
or 
pine = apple,tree 
   
 
 

正则表达式适用于我只有1个值的情况。 但是由于键的值列表中有逗号。 正则表达式只适用于我,我的代码完成了我想要的一半,但没有 获得第二个值。

无论字符串在何处,我都如何修复我的正则表达式以同时使用两个值? 在最后两个之间单独使用。

我尝试了一些东西,但无法弄清楚。

尝试1:

  =([  0-9A-Za-z,_-] +),=?
   
 
 

在这种情况下,它与中间的那个匹配,但在 其他人,因为=不存在。

尝试2:

  = [0-9A-Za-z _-] +([  ,] + [0-9A-Za-z _-] *),?
   
 
 

也匹配bar,pin e和树,例如栏

EDIT ::

这似乎可行。... < 预> <代码> =( '[0-9A-ZA-Z,_-] +'),* | =(0-9A-ZA-Z _-] +),*

如果我使用双引号表示多个值。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dsb0003795 2018-04-04 22:24
    最佳回答

    You can split on variable names - that will leave only the values:

    s := regexp.MustCompile("[^,\\s]+=").Split("foo=bar,pine=apple,tree,bar=bie", -1)
    fmt.Println(s)
    # => [ "bar", "apple,tree", "bie"] 
    

    Go Demo

    Regex Demo

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题