0

Does anyone have an idea on how to convert the following commands into one or fewer commands?

variable = re.search("[a-zA-Z0-9]+[a-zA-Z0-9\-' ]+[a-zA-Z0-9]+", variable).group(0)
variable = re.sub(" {2,}", " ", variable)
variable = re.sub("'{2,}", "'", variable)
variable = re.sub("\-{2,}", "-", variable)

Kind Regards,

Marian

2
  • 1
    I guess it would help a great deal if you posted the strings you are actually trying to match. Commented May 14, 2011 at 20:04
  • I am trying to match something like "Blabla's bla-bla1345", for example. Only alphanumeric are allowed. And space, -, ', but not consecutive and not at the start or end of the string. Commented May 14, 2011 at 21:10

1 Answer 1

1

This is a start:

variable = re.search("[a-zA-Z0-9]+[a-zA-Z0-9\-' ]+[a-zA-Z0-9]+", variable).group(0)
variable = re.sub("([ '\-])\\1+", "\\1", variable)
Sign up to request clarification or add additional context in comments.

5 Comments

Works like a charm. Thank you! :) Btw, can you please explain this part "([ '\-])\\1+", "\\1" ?
\1 (or \\1 because I had to double-escape it) is a reference to the first capture group. That's why I put the '[ '\-]' in parenthesis - to make it a capture group. Now I can repeat it anywhere (in my matches and in my replaces) using \1. I can refer to the second group I define (if I had one) with \2, to the third with \3, etc.
Also, since you're new to stack overflow, I'll kindly remind you to mark this question as answered. :) People here don't like it when askers leave questions unanswered and may not answer your questions in the future if you have a low accepted answers rating. :)
Thank you for your time :) Also, I know I sound kinda silly, but how do I mark my question as answered?
More precisely, mark this answer as accepted; it's that green checkmark icon on the left. By the way, you can use Python's raw strings to cut down on the backslash-itis: re.sub(r"([ '\-])\1+", r"\1", variable)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.