1

I have a piece of code that opens a file and iterates each line inside the formated text file there will be a piece of text like this:

name.x00y00.whatever

I searching for the x00y00 to see if exists, and copy what is found into a string. The problem is that the numbers change, it is always two digits following the 'x' and two digits following the 'y'. But there is no way to predict what those numbers are. What is the best way to search the text with wild cards for it's existance and copy it?

I am completely new to regex so if somebody could enlightenment me I would greatly appreciate it.

4

3 回答 3

2

你可以这样做:

import re
print re.findall(r'\.(x\d{2}y\d{2})\.', "name.x00y00.whatever")
# Prints ['x00y00']

我已经假设name并且whatever也可以更改,并且该x00y00片段始终由点分隔。

\.匹配一个点,\d{2}意思是“两位数”。括号捕获了它们包围的匹配部分。

我正在使用findall以防有多个匹配项。

于 2013-06-07T17:59:20.730 回答
1

像这样的东西:

>>> import re
>>> strs= "name.x00y00.whatever"
>>> match = re.search(r'\.(x\d{2}y\d{2})\.',strs)#returns None if pattern is not found
>>> if match:               
...     print match.group(1)
...     
x00y00
于 2013-06-07T18:00:40.953 回答
0

如果字符串将始终具有.,则对其进行拆分也可以:

>>> s = 'name.x12345y34.foo.bar.zoo'
>>> s.split('.')[1]
'x12345y34'

但是,这假定格式是固定的 - 它始终是第二部分。它不保证结果会有数字,但可能不是必需的。

于 2013-06-07T18:05:38.840 回答