【发布时间】:2021-04-16 10:09:15
【问题描述】:
我正在尝试从Zapier 中的不和谐消息中提取一些值。 消息的内容应该有点像这样(几乎像 YAML):
channel: <#1234567890123456789>
as: Bot nicname
image: http://example.com/
content:
Hello, world!
其中image 和as 字段是可选的。
我创建了 2 个正则表达式来完成这个任务:
Python:
import re
r = re.compile(r"(?:channel:)? ?<#(?P<channel>\d+)>\n+(?:as: ?(?P<as>.+)\n+)?(:?image: ?(?P<image>.+)\n+)?content:\n*(?P<content>[\s\S]+)")
JS:
let r = /(?:channel:)? ?<#(?<channel>\d+)>\n+(?:as: ?(?<as>.+)\n+)?(?:image: ?(?<image>.+)\n+)?content:\n*(?<content>[\s\S]+)/;
我尝试了什么:
在regexr 和pythex 中测试正则表达式。两者都适合我。
然后我将它们输入到 Zapier:
-
In the Text->Formatter by Zapier->Extract pattern - 返回
_matched: false - In the Run Python field
output 来自 python 代码:
groups: null
id: <ID>
runtime_meta:
memory_used_mb: 57
duration_ms: 3
logs:
1. re.compile('(?:channel:)? ?<#(?P<channel>\\d+)>\\n+(?:as: ?(?P<nick>.+)\\n+)?(:?image: ?(?P<image>.+)\\n+)?content:\\n*(?P<content>[\\s\\S]+)')
2. 'channel: <#1234567890123456> \nas: bot nickname\ncontent:\nHello, world!'
3. None
(以及稍后在 Run JavaScript 中获得类似结果)
什么有效(有点):
在尝试调试时,我删除了正则表达式的 image 部分(在 Text->Extract 表达式中):
(?:channel:)? ?<#(?P<channel>\d+)>\n+(?:as: ?(?P<as>.+)\n+)?content:\n*(?P<content>[\s\S]+)
输入:
channel: <#1234567890123456>
as: INFO
content:
Hello, world!
结果如预期:
output:
0: 1234567890123456
1: INFO
2: Hello, world!
_end: 68
_matched: true
_start: 0
as: INFO
channel: 1234567890123456
content: Hello, world!
任何帮助让它工作表示赞赏:)
【问题讨论】:
-
你确定图片部分不超过1个或其他空格?
(?:channel:)? ?<#(?P<channel>\d+)>\n+(?:as:[^\S\r\n]*(?P<as>.+)\n+)?(:?image:[^\S\r\n]*(?P<image>.+)\n+)?content:\n*(?P<content>[\s\S]+)regex101.com/r/mxrs0Z/1 -
@Thefourthbird 我检查了你的正则表达式,它也没有匹配。 1 或其他空格是什么意思?我插入了打印提供给格式化程序的内容的 (python) repr() 的代码,它是:
channel: <#12345678901234567> \nas: This is test\nimage: http://www.example.com/\ncontent:\nHello, world! -
因为
` ?` 匹配 0 或 ` 空格。我觉得>后面还有个空格可以试试regex101.com/r/wCKAta/1 -
就是这样!至少对于最后一个输入它有效!我会检查其他的,让你知道。您可以将此作为答案发布,如果可行,我会接受。 :)
-
是的!非常感谢