首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >匹配多个短语的正则表达式

匹配多个短语的正则表达式
EN

Stack Overflow用户
提问于 2020-10-22 03:02:11
回答 1查看 132关注 0票数 1

我正在寻找一个正则表达式,它可以帮助我从长字符串中获得字符串子集,而无需多次运行拆分方法,所以我想我可以使用regex,但目前我失败了。

这是我的输入文本:

代码语言:javascript
运行
复制
Platform->Not Machine Specific Studio->Symantec Title->Symantec Promotional Book Home Internet Security

这是我用regexp做的尝试

尝试1

regexp:/[A-Z]+->([A-Z]+|[0-9]+)(\s*|([A-Z]|[0-9])+)*$/gim

结果:Title->Symantec Promotional Book Home Internet Security

尝试2

regexp:/[A-Z]+->([A-Z]+|[0-9]+)(\s*|([A-Z]|[0-9])+)*/gim

结果:

代码语言:javascript
运行
复制
Platform->Not Machine Specific Studio

Title->Symantec Promotional Book Home Internet Security

预期结果:

代码语言:javascript
运行
复制
Platform->Not Machine Specific 

Studio->Symantec    

Title->Symantec Promotional Book Home Internet Security

结果中的每一行都应该是匹配的

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-22 03:10:51

您可以尝试以下regex模式:

代码语言:javascript
运行
复制
\S+->.*?(?= \S+->|$)

Demo

下面是对这种模式的解释:

代码语言:javascript
运行
复制
\S+           match an initial key
->            match "->"
.*?           match a value, consisting of one or possibly more words, under reaching
(?= \S+->|$)  the next key followed by "->" OR the end of the string

编辑:

如果您是通过Python脚本执行此操作的,那么我建议在这里使用re.findall

代码语言:javascript
运行
复制
inp = "Platform->Not Machine Specific Studio->Symantec Title->Symantec Promotional Book Home Internet Security"
matches = re.findall(r'\S+->.*?(?= \S+->|$)', inp)
print(matches)

这些指纹:

代码语言:javascript
运行
复制
['Platform->Not Machine Specific', 'Studio->Symantec',
 'Title->Symantec Promotional Book Home Internet Security']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64474617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档