【问题标题】:python, split, regex and combine repython,拆分,正则表达式和组合重新
【发布时间】:2021-12-24 22:50:23
【问题描述】:

我有一个键值格式的数据。

key=1234 key1="value in text"

我想创建单个正则表达式来拆分单个键的值。

例如:

  • key={regex} 必须返回 1234
  • key1={regex} 必须返回“文本中的值”
regex="key=\"(.*?)\"|key=([^ ]*)"

我已经尝试过这个正则表达式,但它不起作用。你能帮帮我吗?

我想通过帮助 regex 和 spark 以这种方式拆分字符串以获取表格格式的结果。

键 |键1 | 值|文本中的值|

【问题讨论】:

  • 您能否在 python 中提供可重现的数据。即我们可以复制并粘贴到python中的东西。 string = 'key=1234 key1="value in text"' 你的数据是这样的吗?
  • 您为什么要使用正则表达式?使用字符串方法解析成 dict 是微不足道的。

标签: python-3.x regex pyspark


【解决方案1】:

您可以使用PyPi regex library 和类似的代码

import regex
text = 'key=1234 key1="value in text"'
# key = 'key1' # => value in text
key = 'key' # => 1234
pattern = fr'\b{regex.escape(key)}=(?|"([^"]*)"|(\S*))'
match = regex.search(pattern, text)
if match:
    print(match.group(1)) # => 1234

请参阅online Python demo详情

  • \b - 单词边界
  • {regex.escape(key)} - 传递给正则表达式的密钥
  • = - 等号
  • (?|"([^"]*)"|(\S*)) - 一个 branch reset group 匹配
    • "([^"]*)" - 一个 " 字符,然后是除 " 之外的零个或多个字符被捕获到第 1 组,然后是一个 " 字符
    • | - 或
    • (\S*) - 第 1 组(同样,因为它是一个分支重置组):零个或多个非空白字符。

这是我的 "Branch reset groups - capture different patterns into same groups" YT 视频,展示了分支重置组的使用。

【讨论】:

  • 如果我想拆分 key=value 对并从中获取值怎么办
  • @AnuRadha 不明白你的意思。如果你想得到key=value,只需返回match.group(),整个匹配。
  • 我想拆分字符串,想把键值对转换成表格格式。钥匙 |键1 |价值 |文本中的值 |
  • @AnuRadha 您刚刚将您的问题“转换”为一个新问题。 pyspark 是完全不同的一壶鱼。
【解决方案2】:

如果字符串的上下文是有效的,即键之后的所有内容都只是封装在引号内,那么我更愿意将字符串解析为字典并获取所需的值:

import re

string = 'key=1234 key1="value in text"'
replace =  lambda x: (', ' if x.group(1) else '') + f'"{x.group(2)}":'

my_dict = eval(re.sub(r'(\s)?(\w+)=',replace, f"{{{string}}}"))

my_dict['key']
# out[23] 1234

my_dict['key1']
# out[24] 'value in text'

【讨论】:

    猜你喜欢
    • 2021-10-07
    • 2012-04-20
    • 2021-08-15
    • 2019-01-25
    • 2012-01-18
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多