我有一個可以由其他人更改的字串格式(只是說)
sample = f"This is a {pet} it has {number} legs"
我目前有兩個字串
a = "This is a dog it has 4 legs"
b = "This was a dog"
如何檢查哪個字串滿足這種sample格式?我可以使用python的字串replace()并sample創建它的正則運算式并使用re.match進行檢查。但是問題是sample可以更改的,因此靜態使用replace并不總是有效,因為sample可能會獲得更多的占位符。
uj5u.com熱心網友回復:
一個簡單的提取物件的小方法是
import re
patt = re.compile(r'This is a (. ) it has (\d ) legs',)
a = "This is a dog it has 4 legs"
b = "This was a dog"
match = patt.search(a)
print(match.group(1), match.group(2))
uj5u.com熱心網友回復:
我喜歡這些方法,但我找到了兩個線性解決方案:(我不知道這個的性能方面,但它有效!)
def pattern_match(input, pattern):
regex = re.sub(r'{[^{]*}','(.*)', "^" pattern "$")
if re.match(regex, input):
print(f"'{input}' matches the pattern '{pattern}'")
pattern_match(a, sample)
pattern_match(b, sample)
輸出
'This is a dog it has 4 legs' matches the pattern 'This is a {pet} it has {number} legs'
uj5u.com熱心網友回復:
試試這個。
sample = "This is a {pet} it has {number} legs"
def check(string):
patt = sample.split(' ')
index = [i for i,v in enumerate(patt) if '{' in v and '}' in v]
if all(True if v==patt[i] or i in index else False for i,v in enumerate(string.split(' '))):
print(f'string matches the pattern')
else:
print(f"string does not match the pattern")
a = "This is a dog it has 4 legs"
b = "This was a dog"
check(a) # string matches the pattern
uj5u.com熱心網友回復:
首先,如果要匹配模板字串,請不要使用f''字串前綴,否則將立即對其進行評估。相反,只需撰寫格式字串,如:
sample = 'This is a {pet} it has {number} legs'
這是我為一個專案撰寫的用于決議格式字串并將其轉換為正則運算式的函式:
import re
import string
def format_to_re(format_str, **kwargs):
r"""
Convert a format string to a regular expression, such that any format
fields may replaced with regular expression syntax, and any literals are
properly escaped.
As a special case, if a 2-tuple is given for the value of a field, the
first time the field appears in the format string the first element of the
tuple is used as the replacement, and the second element is used for all
subsequence replacements.
Examples
--------
This example uses a backslash just to add a little Windows flavor:
>>> filename_format = \
... r'scenario_{scenario}\{name}_{scenario}_{replicate}.npz'
>>> filename_re = format_to_re(filename_format,
... scenario=(r'(?P<scenario>0*\d )', r'0*\d '),
... replicate=r'0*\d ', name=r'\w ')
>>> filename_re
'scenario_(?P<scenario>0*\\d )\\\\\\w _0*\\d _0*\\d \\.npz'
>>> import re
>>> filename_re = re.compile(filename_re)
>>> filename_re
re.compile(...)
This regular expression can be used to match arbitrary filenames to
determine whether or not they are in the format specified by the original
``filename_format`` template, as well as to extract the values of fields by
using groups:
>>> match = filename_re.match(r'scenario_000\my_model_000_000.npz')
>>> match is not None
True
>>> match.group('scenario')
'000'
>>> filename_re.match(r'scenario_000\my_model_garbage.npz') is None
True
"""
formatter = string.Formatter()
new_format = []
seen_fields = set()
for item in formatter.parse(format_str):
literal, field_name, spec, converter = item
new_format.append(re.escape(literal))
if field_name is None:
continue
replacement = kwargs[field_name]
if isinstance(replacement, tuple) and len(replacement) == 2:
if field_name in seen_fields:
replacement = replacement[1]
else:
replacement = replacement[0]
new_format.append(replacement)
seen_fields.add(field_name)
return ''.join(new_format)
您可以在示例中使用它,例如:
>>> sample_re = format_to_re(sample, pet=r'(?P<pet>. )', number=r'(?P<number>\d )')
>>> sample_re = re.compile(sample_re)
>>> sample_re
re.compile('This\\ is\\ a\\ (?P<pet>. )\\ it\\ has\\ (?P<number>\\d )\\ legs')
>>> m = sample_re.match('This is a dog it has 4 legs')
>>> m.groupdict()
{'pet': 'dog', 'number': '4'}
根據您的用例,您可以稍微簡化一下。最初的版本是為了處理一些特定于應用程式的情況。
另一個可能的增強是,給定任意格式字串,為其中找到的每個欄位提供默認正則運算式,可能由欄位中的任何格式說明符確定。
uj5u.com熱心網友回復:
當你運行時:
sample = f"This is a {pet} it has {number} legs"
樣本沒有任何占位符
Sample 是"This is a xxx it has yyy legs"已經被替換xxx的字串。yyy因此,除非您知道哪些是引數,否則您無能為力。
如果您想要占位符,請不要使用 f 字串:
sample = "This is a {pet} it has {number} legs"
formatted_string = sample.format(**{'pet': 'dog', 'number': '4'})
# "This is a dog it has 4 legs"
然后你可以運行類似的東西:
import string
from operator import itemgetter
sample = "This is a {pet} it has {number} legs"
keys = {k: r'\w ' for k in filter(None,
map(itemgetter(1), string.Formatter().parse(sample)))}
# {'pet': '\\w ', 'number': '\\w '}
regex = re.compile(sample.format(**keys))
a = "This is a dog it has 4 legs"
b = "This was a dog"
regex.match(a)
# <re.Match object; span=(0, 27), match='This is a dog it has 4 legs'>
regex.match(b)
# None
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479800.html
上一篇:如何決議給定的鍵值引數字串?
