Python pattern match a string

时间:2017-07-10 15:19:21

标签: python python-2.7

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.

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.

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

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

2 个答案:

答案 0 :(得分:4)

You're confused about how to use regular expressions here. Your code is saying "search the string 'std' for any alphanumeric character".

But there is no need to use regexes here anyway. Just use string slicing, and .endswith:

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

答案 1 :(得分:3)

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)