我有以下字符串:
s = '''Report:
Location: (569P,921L)
Band 1:
Value: 12'''
我必须得到以下内容:
x, y = 569, 921
最好和最简单的方法是什么?
我不喜欢re
因为使用它的复杂和令人困惑的角色。
我已成功提取了我要求的内容如下:
x, y = int(s.split()[2].split(',')[0][1:-1]), int(s.split()[2].split(',')[1][:-2])
但您的想法受到高度赞赏。
答案 0 :(得分:0)
Report:\s*Location:\s*\(([0-9]*)P,([0-9]*)L\)\s*Band 1:\s*Value: 12
此正则表达式适用于您的案例
完整代码:
m = re.match(
r"Report:\s*Location:\s*\(([0-9]*)P,([0-9]*)L\)\s*Band 1:\s*Value: 12",
your_string)
m.group(0) # First Number
m.group(1) # Second Number`
答案 1 :(得分:0)
这个简单的正则表达式适用于这种情况。
>>> s = '''Report:
Location: (569P,921L)
Band 1:
Value: 12'''
>>> x,y = re.findall(r'\b\d+(?=[A-Z])', s)
>>> print(x,y)
569 921
\b
在单词字符和非单词字符之间匹配的单词边界。 \d+
匹配一个或多个数字(?=[A-Z])
,后面必须跟一个大写字母。
答案 2 :(得分:0)
通过字符串查找方法:
定位介于(
和)
import traceback
lines = input.split("\n")
result = []
for i in lines:
start_index = i.find("(")
if start_index!=-1:
end_index = i.find(")", start_index)
if end_index!=-1:
taget_content = i[start_index+1: end_index]
tmp = taget_content.split(",")
try:
x = int(tmp[0][:-1])
y = int(tmp[1][:-1])
result.append((x,y))
except:
print "Exception during eval:-", traceback.format_exc()
print result
输出:
$ python test.py
[(569, 921), (600, 900)]
通过正则表达式
input = '''Report:
Location: (569P,921L)
Band 1:
Value: 12
Location: (600P,900L)
Band 1:
Value: 12
'''
import re
target = re.findall("\((.*)\)", input)
print "target content:-", target
result = []
for i in target:
tmp = i.split(",")
try:
result.append((int(tmp[0][:-1]), int(tmp[1][:-1])))
except:
print "Exception during eval:-", traceback.format_exc()
print "Result:-", result
输出:
$ python test.py
target content:- ['569P,921L', '600P,900L']
Result:- [(569, 921), (600, 900)]