匹配>>数字并替换它

时间:2014-06-18 19:40:13

标签: python regex

我有一个包含>>number格式的单词的字符串。

例如:

this is a sentence >>82384324

我需要一种匹配>>numbers的方法,并将其替换为包含该数字的另一个字符串。

例如:>>342变为

this is a string that contains the number 342

5 个答案:

答案 0 :(得分:2)

s= "this is a sentence >>82384324"
print re.sub("(.*\>\>)","This is a string containing " ,s)
This is a string containing 82384324

答案 1 :(得分:2)

假设你要在一个字符串中遇到多个次数,我会建议一些更强大的东西,例如:

import re

pattern = re.compile('>>(\d+)')
str = "sadsaasdsa >>353325233253 Frank >>352523523"

search = re.findall(pattern, str)
for each in search:
    print "The string contained the number %s" % each

哪个收益率:

>>The string contained the number 353325233253
>>The string contained the number 352523523

答案 2 :(得分:1)

使用这种基本模式应该有效:

>>(\d+) 

代码:

import re

str = "this is a sentence >>82384324"
rep = "which contains the number \\1"
pat = ">>(\\d+)"
res = re.sub(pat, rep, str)

print(res)

示例:http://regex101.com/r/kK3tL8

答案 3 :(得分:1)

您可以使用以下方式执行此操作:

sentence = 'Stringwith>>1221'

print 'This is a string that contains
the number %s' % (re.search('>>(\d+)',sentence).group(1))

结果:

This is a string that contains the number 1221

您可以查看findall选项以获取与模式here

匹配的所有数字

答案 4 :(得分:1)

一种简单的方法,假设您找到的唯一地方">>"在数字之前,是替换那些:

>>> mystr = "this is a sentence >>82384324"
>>> mystr.replace(">>","this is a string that contains the number ")
'this is a sentence this is a string that contains the number 82384324'

如果还有>>的其他示例在您不想替换的文本中,您还需要捕获该数字,并且最好使用正则表达式。

>>> import re
>>> re.sub('>>(\d+)','this is a string that contains the number \g<1>',mystr)
'this is a sentence this is a string that contains the number 82384324'

https://docs.python.org/2/library/re.htmlhttps://docs.python.org/2/howto/regex.html可以提供有关正则表达式的更多信息。