python - 正则表达式匹配函数参数

标签 python regex

select\[([^\s]*(?<param>[a-z0-9]+)[^,\s]*)*\]

尝试从逗号分隔的参数加载捕获组(数字或字母数字选项),忽略每个参数的前导/尾随空格,但保留单词之间的空格(即“两个单词”)。

select[  1, 22 ,word,      two words    ]

成为:

param1: "1"
param2: "22"
param3: "word"
param4: "two words"

RegEx101

一旦排序,想要处理参数周围的可选单引号'。

感谢您的考虑

最佳答案

另一种用于支持 \G 的引擎:

(?:\G(?!\A)|select\[)        # look for the last match or select[
\s*                          # whitespaces, optional and greedy
((?:(?!(?:[ ]{2,}|\]|,)).)+) # not overrunning two consecutive spaces, ] or ,
\s*                          # another greedy whitespace
(?:,|\])                     # , or ]

劫持您的演示: https://regex101.com/r/a0ab0Q/8

<小时/> 您可能想要删除两侧的空格,这可以做到(使用即 Python):

import regex as re
rx = re.compile(r'''
        (?:\G(?!\A)|select\[)
        \s*
        ((?:(?!(?:[ ]{2,}|\]|,)).)+)
        \s*
        (?:,|\])
''', re.VERBOSE)

params = [match.group(1).strip()
          for match in rx.finditer(string)]
print(params)
# ['1', '22', 'word', 'two words']

关于python - 正则表达式匹配函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708719/

相关文章:

python - Django 类型错误 : __init__() takes 1 positional argument but 2 were given

python - 从 Python Shell 运行 Python 脚本

regex - 从文章中提取段落 |正则表达式

python正则表达式重复组匹配

python - 解析 git - 使用 python 的日志文件

python分解一个列表

python - 如何将变量从 NodeJs 插入到 python 脚本中?

python - 类型错误 : attrib() got an unexpected keyword argument 'convert'

regex - 在映射文件中对多列使用 ReplaceTextWithMapping

正则表达式检查第一个子文件夹是否为 "print"