在python正则表达式中匹配括号

时间:2022-02-25 22:25:20

I have something like

我有类似的东西

store(s)

商店(S)

ending line like 1 store(s) .. I want to match , it using python regular expression.

像1商店的结束行..我想匹配,它使用python正则表达式。

I tried something like re.match('store\(s\)$',text) but it's not working .

我试过像re.match('store \(s \)$',text)这样的东西,但它没有用。

EDIT : adding the code , I tried

编辑:添加代码,我试过

import re
s = '1 store(s)'
if re.match('store\(s\)$',s) :
    print('match')

Pls help.

请帮忙。

Thanks Jijoy

谢谢Jijoy

3 个解决方案

#1


6  

In more or less direct reply to your comment

或多或少直接回复您的评论

Try this

尝试这个

import re
s = '1 stores(s)'
if re.match('store\(s\)$',s):
    print('match')

The solution is to use re.search instead of re.match as the latter tries to match the whole string with the regexp while the former just tries to find a substring inside of the string that does match the expression.

解决方案是使用re.search而不是re.match,因为后者尝试将整个字符串与regexp匹配,而前者只是尝试在字符串内部找到与表达式匹配的子字符串。

#2


1  

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default)

Python提供了两种基于正则表达式的不同原语操作:匹配仅在字符串的开头检查匹配,而搜索在字符串中的任何位置检查匹配(这是Perl默认执行的操作)

Straight from the docs, but it does come up alot.

直接来自文档,但它确实出现了很多。

#3


0  

have you considered re.match('(.*)store\(s\)$',text) ?

你考虑过re.match('(。*)store \(s \)$',text)?

#1


6  

In more or less direct reply to your comment

或多或少直接回复您的评论

Try this

尝试这个

import re
s = '1 stores(s)'
if re.match('store\(s\)$',s):
    print('match')

The solution is to use re.search instead of re.match as the latter tries to match the whole string with the regexp while the former just tries to find a substring inside of the string that does match the expression.

解决方案是使用re.search而不是re.match,因为后者尝试将整个字符串与regexp匹配,而前者只是尝试在字符串内部找到与表达式匹配的子字符串。

#2


1  

Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default)

Python提供了两种基于正则表达式的不同原语操作:匹配仅在字符串的开头检查匹配,而搜索在字符串中的任何位置检查匹配(这是Perl默认执行的操作)

Straight from the docs, but it does come up alot.

直接来自文档,但它确实出现了很多。

#3


0  

have you considered re.match('(.*)store\(s\)$',text) ?

你考虑过re.match('(。*)store \(s \)$',text)?