如何检查字符串是否与 Python 中的设置模式匹配? [英] How do I check if a string matches a set pattern in Python?

查看:63
本文介绍了如何检查字符串是否与 Python 中的设置模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个字符串与特定模式或一组词进行匹配,如下所示:

I want to match a string to a specific pattern or set of words, like below:

the apple is red 是查询和apple|orange|grape is red|orange|violet 是要匹配的模式.管道将代表可以相互替换的单词.模式也可以像 [launch app]|[start program] 那样分组.无论查询是否与模式匹配,我都希望模块自然地返回 True 或 False.

the apple is red is the query and the apple|orange|grape is red|orange|violet is the pattern to match. The pipes would represent words that would substitute each other. The pattern could also be grouped like [launch app]|[start program]. I would like the module to return True or False whether the query matches the pattern, naturally.

如果还没有一个图书馆可以做到这一点,那么最好的方法是什么?如果这可以用简单的正则表达式来完成,那就太好了;但是我对正则表达式几乎一无所知.我使用的是 Python 2.7.11

What is the best way to accomplish this if there is not a library that does this already? If this can be done with simple regex, great; however I know next to nothing about regex. I am using Python 2.7.11

推荐答案

import re

string = 'the apple is red'

re.search(r'^the (apple|orange|grape) is (red|orange|violet)', string)

这是它运行的一个例子:

Here's an example of it running:

In [20]: re.search(r'^the (apple|orange|grape) is (red|orange|violet)', string). groups()
Out[20]: ('apple', 'red')

如果没有匹配项,则 re.search() 将不返回任何内容.

If there are no matches then re.search() will return nothing.

您可能对正则表达式几乎一无所知";但你差点写出模式.

You may know "next to nothing about regex" but you nearly wrote the pattern.

括号内的部分也可以有自己的正则表达式模式.所以你可以匹配apple"和苹果"与

The sections within the parentheses can also have their own regex patterns, too. So you could match "apple" and "apples" with

r'the (apple[s]*|orange|grape)

这篇关于如何检查字符串是否与 Python 中的设置模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆