简体   繁体   English

Python模式匹配字符串

[英]Python pattern match a string

I am trying to pattern match a string, so that if it ends in the characters 'std' I split the last 6 characters and append a different prefix. 我正在尝试对字符串进行模式匹配,以便如果它以字符'std'结尾,我将分割最后6个字符并附加一个不同的前缀。

I am assuming I can do this with regular expressions and re.split, but I am unsure of the correct notation to append a new prefix and take last 6 chars based on the presence of the last 3 chars. 我假设我可以使用正则表达式和re.split来做到这一点,但是我不确定追加新前缀并根据后3个字符的存在取后6个字符的正确表示法。

regex = r"([a-zA-Z])"
if re.search(regex, "std"):
    match = re.search(regex, "std")

#re.sub(r'\Z', '', varname)

You're confused about how to use regular expressions here. 您对这里如何使用正则表达式感到困惑。 Your code is saying "search the string 'std' for any alphanumeric character". 您的代码说“在字符串'std'中搜索任何字母数字字符”。

But there is no need to use regexes here anyway. 但是无论如何,这里不需要使用正则表达式。 Just use string slicing, and .endswith : 只需使用字符串切片,然后使用.endswith

if my_string.endswith('std'):
    new_string = new_prefix + mystring[-6:]

No need for a regex. 无需正则表达式。 Just use standard string methods: 只需使用标准的字符串方法:

if s.endswith('std'):
    s = s[:-6] + new_suffix

But if you had to use a regex, you would substitute a regex, you would substitute the new suffix in: 但是,如果必须使用正则表达式,则可以替换为正则表达式,也可以替换为以下内容中的新后缀:

regex = re.compile(".{3}std$")

s = regex.sub(new_suffix, s)

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

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