![](/img/trans.png)
[英]Extract words between the word “for” and the opening parenthesis “(” in an email subject line. Email subject line is the input
[英]How to pull words between starting word till '\n' new line. and is there any way to put 'OR' condition while extracting words in python?
{mtd: LAct, cId: _M_, cTy: 300}
cId: ['2', '103', '201', '202', '1', '101']
cTy: 428
mtd: PAct
cId: ['104']
cTy: 428
mtd: CAct
cId: ['104']
cTy: 428
这是我拥有的一种文本,希望从方括号中获取LAct、PAct、CAct和'2'、'101'等数字
我正在正则表达式评估门户网站 (regex101.com) 上尝试类似的方法
(?<=cSId:).*?[\n]
但是当我在 python (re module) 中使用相同的时候这不起作用
re.findall('((?<=contentSourceId:).*?[\n]',myst)
两个问题: 1. 如何获得 LAct、PAct、CAct 的值 2. 有没有办法将“OR”条件放在我只想获取数字而不是_M__ 的多个“cId”、“mtd”场景中
您可以使用
\b(?:cId|mtd):\s*(\[[^][]+]|[^\W_]+)
提取您想要的值,然后检查捕获的文本是否以[
开头,并相应地解析结果。
注意:这个re
+ ast
解决方案只有在[...]
中的值总是已知的、逗号分隔的单引号包裹数字时才有效。
请参阅正则表达式演示:
\\b
- 单词边界(?:cId|mtd)
- cId
或mtd
:
- 一个冒号\\s*
- 0+ 个空格(\\[[^][]+]|[^\\W_]+)
- 第 1 组(它是re.findall
返回的值,其余被视为上下文):
\\[[^][]+]
- [
,除[
和]
之外的 1+ 个字符,然后是]
|
- 或者[^\\W_]+
- 1 个或多个字母数字字符import re, ast
text = "{mtd: LAct, cId: _M_, cTy: 300}\n cId: ['2', '103', '201', '202', '1', '101']\n cTy: 428\n mtd: PAct\n cId: ['104']\n cTy: 428\n mtd: CAct\n cId: ['104']\n cTy: 428"
res = [];
for m in re.findall(r"\b(?:cId|mtd):\s*(\[[^][]+]|[^\W_]+)", text):
if m.startswith("["):
res.append(ast.literal_eval(m.replace("'", '')))
else:
res.append(m)
print(res) # => ['LAct', [2, 103, 201, 202, 1, 101], 'PAct', [104], 'CAct', [104]]
如果您需要['LAct', 2, 103, 201, 202, 1, 101, 'PAct', 104, 'CAct', 104]
作为结果,请使用res.extend(ast.literal_eval(m.replace("'", '')))
,请参阅此 Python 演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.