【问题标题】:Regex to capture key-value comma-separated values正则表达式捕获键值逗号分隔值
【发布时间】:2015-09-25 23:33:48
【问题描述】:

我正在尝试编写一个正则表达式来解析 Unrealscript 序列化对象中的值。其中一部分涉及这样的行:

(X=32.69,Y='123.321',Z="A string with commas, just to complicate things!",W=Class'Some.Class')

最终的捕获应该是:

[
    {
        'X':32.69,
        'Y':'A string with commas, just to complicate things!',
        'Z':'Class\'Some.Class\'
    }
]

我想要的是能够区分键(例如X)和值(例如Class\'Some.Class\')。

这是我迄今为止尝试过的一种模式,只是为了捕获一组简单的值(目前不尝试处理值内部的逗号):

图案

\(((\S?)=(.+),?)+\)

数据集

(X=32,Y=3253,Z=12.21)

结果

https://regex101.com/r/gT9uU3/1

我仍然是这些正则表达式的新手,任何帮助将不胜感激!

提前致谢。

【问题讨论】:

  • 你能强调一下What I want is to be able to distinguish between the key (eg. X) and the value (eg. Class'Some.Class').
  • 确实,描述很模糊。你想把所有的'内部值变成\'吗?你想把所有“周围的值都变成”吗?你有任意数量的值吗?什么引擎/编程语言?如果你确定你的数据会是什么样子并且你不是在追求高级的东西,那么也许你可以用正则表达式实现这一点。如果你想转义任意数量的引号等,那么这个任务不太适合正则表达式(至少不是一个)。

标签: regex unrealscript


【解决方案1】:

你可以试试这个正则表达式来关联键值对:

(?!^\()([^=,]+)=([^\0]+?)(?=,[^,]+=|\)$)

Regex live here.

解释:

(?!^\()         # do not match the initial '(' character

([^=,]+)        # to match the key .. we take all from the last comma
=               # till the next '=' character

([^\0]+?)       # any combination '[^\0]' - it will be the key's value
                  # at least one digit '+'
                  # but stops in the first occurrence '?'

(?=             # What occurrence?

    ,[^,]+=     # a comma ',' and a key '[^,]+='
                  # important: without the key:
                  # the occurrence will stop in the first comma
                  # that should or should not be the delimiter-comma 

    |\)$        # OR '|':  the value can also be the last one
                  # which has not another key in sequence,
                  # so, we must accept the value
                  # which ends '$' in ')' character

)               # it is all

希望对你有帮助。

对不起我的英语,请随时编辑我的解释,或在 cmets 中告诉我。 =)

【讨论】:

  • 你是救世主。现在我需要研究一下它是如何工作的!
  • @cmbasnett。希望你明白解释
猜你喜欢
  • 1970-01-01
  • 2021-05-31
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多