我有一个像这样的字符串
line = u'I need to match the whole line except for {thisword for example'
我很难做到这一点。我已经尝试过但不起作用:
# in general case there will be Unicode characters in the pattern
matchobj = re.search(ur'[^\{].+', line)
matchobj = re.search(ur'(?!\{).+', line)
您能帮我找出问题所在以及如何正确处理吗?
附注我认为我不需要用空字符串替换 "{thisword"
最佳答案
我不太清楚你需要什么。从你的问题标题来看,你似乎想找到“字符串中的所有单词,例如‘line’,这些单词不以 { 开头”,但你正在使用 re.search() 函数,这让我感到困惑。
re.search()
和re.findall()
函数 re.search()
返回 a 对应的 MatchObject 实例,re.serach 通常用于匹配并返回长字符串中的模式。 它不会返回所有可能的匹配项。请参阅下面的一个简单示例:
>>> re.search('a', 'aaa').group(0) # only first match
'a'
>>> re.search('a', 'aaa').group(1) # there is no second matched
Traceback (most recent call last):
File "<console>", line 1, in <module>
IndexError: no such group
使用正则表达式'a'
搜索仅返回一个模式 'a'
字符串 'aaa'
,它不会返回所有可能的匹配项。
如果您的目标是查找 - “字符串中所有不以 {
开头的单词”。您应该使用 re.findall()
函数:- 匹配模式的所有出现,而不是像 re.search() 那样只匹配第一个模式。请参阅示例:
>>> re.findall('a', 'aaa')
['a', 'a', 'a']
编辑:在评论的基础上添加一个示例来演示 re.search 和 re.findall 的使用:
>>> re.search('a+', 'not itnot baaal laaaaaaall ').group()
'aaa' # returns ^^^ ^^^^^ doesn't
>>> re.findall('a+', 'not itnot baaal laaaaaaall ')
['aaa', 'aaaaaaa'] # ^^^ ^^^^^^^ match both
这里有一个很好的 Python re 模块教程:re – Regular Expressions
此外,Python-regex 中还有组的概念——“括号内的匹配模式”。如果您的正则表达式模式中存在多个组,则 re.findall() 返回一组组列表;如果模式有多个组,这将是一个元组列表。见下文:
>>> re.findall('(a(b))', 'abab') # 2 groups according to 2 pair of ( )
[('ab', 'b'), ('ab', 'b')] # list of tuples of groups captured
在 Python 正则表达式中 (a(b))
包含两组;作为两对括号(这与正式语言中的正则表达式不同 - 正则表达式与正则表达式并不完全相同
用正式语言表达,但那是另一回事)。
答案:句子中的单词line
用空格分隔(其他在字符串开头)正则表达式应该是:
ur"(^|\s)(\w+)
正则表达式描述:
-
(^|\s+)
意思是:要么在开头的单词,要么在一些空格之后开始。 -
\w*
:匹配字母数字字符,包括“_”。
关于应用正则表达式 r
到您的线路:
>>> import pprint # for pretty-print, you can ignore thesis two lines
>>> pp = pprint.PrettyPrinter(indent=4)
>>> r = ur"(^|\s)(\w+)"
>>> L = re.findall(r, line)
>>> pp.pprint(L)
[ (u'', u'I'),
(u' ', u'need'),
(u' ', u'to'),
(u' ', u'match'),
(u' ', u'the'),
(u' ', u'whole'),
(u' ', u'line'),
(u' ', u'except'),
(u' ', u'for'), # notice 'for' after 'for'
(u' ', u'for'), # '{thisword' is not included
(u' ', u'example')]
>>>
要查找一行中的所有单词,请使用:
>>> [t[1] for t in re.findall(r, line)]
注意:它将避免使用 { 或行中的任何其他特殊字符,因为\w 只传递字母数字和 '_' 字符。
<小时/>如果您专门只避免 {
如果它出现在单词的开头(允许在中间),则使用正则表达式:r = ur"(^|\s+)(?P<word>[^{]\S*)"
。
要了解此正则表达式与其他正则表达式之间的差异,请检查此示例:
>>> r = ur"(^|\s+)(?P<word>[^{]\S*)"
>>> [t[1] for t in re.findall(r, "I am {not yes{ what")]
['I', 'am', 'yes{', 'what']
<小时/>
没有正则表达式:
无需任何正则表达式即可实现相同的效果,如下所示:
>>> [w for w in line.split() if w[0] != '{']
<小时/>
re.sub() 替换模式
如果您只想替换一个(或多个)以 {
开头的单词你应该使用 re.sub()
替换以 {
开头的模式通过空字符串""
检查以下代码:
>>> r = ur"{\w+"
>>> re.findall(r, line)
[u'{thisword']
>>> re.sub(r, "", line)
u'I need to match the whole line except for for example'
<小时/>
编辑添加评论回复:
(?P<name>...)
是Python的正则表达式扩展:(它在Python中有意义)- (?P<name>...)
与常规括号类似 - 创建一个组(命名组)。可通过符号组名称访问该组。组名称必须是有效的 Python 标识符,并且每个组名称只能在正则表达式中定义一次。示例 1:
>>> r = "(?P<capture_all_A>A+)"
>>> mo = re.search(r, "aaaAAAAAAbbbaaaaa")
>>> mo.group('capture_all_A')
'AAAAAA'
示例2:假设您想从可能包含标题的名称行中过滤名称,例如 mr 使用正则表达式:name_re = "(?P<title>(mr|ms)\.?)? ?(?P<name>[a-z ]*)"
我们可以使用 group('name')
读取输入字符串中的名称:
>>> re.search(name_re, "mr grijesh chauhan").group('name')
'grijesh chauhan'
>>> re.search(name_re, "grijesh chauhan").group('name')
'grijesh chauhan'
>>> re.search(name_re, "ms. xyz").group('name')
'xyz'
关于python - 匹配字符串中除 python 中大括号前面的任何单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23030330/