Pectus Excavatum
Pectus Excavatum

Reputation: 3783

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.

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)

Upvotes: 0

Views: 101

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599610

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:]

Upvotes: 4

Artyer
Artyer

Reputation: 40811

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)

Upvotes: 3

Related Questions