简体   繁体   English

从 python 中给出的字符串中提取模式

[英]Extract a pattern from the string given below in python

string_input = 'HijesProvincia:GuadalajaraUTM X:499.028CC.AA.:Comunidad Autónoma de Castilla-La ManchaUTM Y:4.567.841Huso:30Cota:1244 m.s.n.m.Tipo de punto:'

In this string I have to extract UTM X:499.028 and UTM Y:4.567.841 .在这个字符串中,我必须提取UTM X:499.028UTM Y:4.567.841

I want a generalized way to parse this format because the numbers will be of different length.我想要一种通用的方法来解析这种格式,因为数字的长度不同。 But all the string inputs will be of similar structure.但是所有字符串输入都将具有相似的结构。

Use regular expressions.使用正则表达式。 Depending on whether the text in between is fixed or variable, you can insert it as is in your pattern, or use \.+ :根据中间的文本是固定的还是可变的,您可以将其按原样插入到您的模式中,或使用\.+

>>> import re

>>> p = re.compile('HijesProvincia:Guadalajara(UTM X:[0-9.]+).+(UTM Y:[0-9.]+)')
>>> m = p.search(string_input)
>>> m.groups()
('UTM X:499.028', 'UTM Y:4.567.841')

Note that I use [0-9.]+ instead of \d+ to match the number.请注意,我使用[0-9.]+而不是\d+来匹配数字。 I included the dot because the number of dots seems variable in your example.我包括了点,因为在您的示例中点的数量似乎是可变的。

You should detail the precise pattern that can appear and how much the string around it can change.您应该详细说明可能出现的精确模式以及它周围的字符串可以改变多少。 But assuming you search for 'UTM X:' or 'UTM Y:' followed by a sequence of digits groups separated by a dot in a generic string you can use:但假设您搜索“UTM X:”或“UTM Y:”后跟一系列数字组,这些数字组在通用字符串中由点分隔,您可以使用:

import re 
...
re.findall('(UTM [XY]:[\d.]+)', string_input)

that returns a list:返回一个列表:

['UTM X:499.028', 'UTM Y:4.567.841']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM