Python Forum

Full Version: Regex excluding
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How could I use regex to match everything not in between hyphens? E.g. re.search(r"<>", "- i don't want this - I do want this")

Edit: This particular example is simple, and could be solved using re.split() -- but that won't generally work
Replace the bits you don't want with nothing.

target = "Stuff at front - i don't want this - I do want this"
wanted = re.sub(r'-.*-', '', target)
print(wanted)
Output:
Stuff at front I do want this
You can do it without regex with str methods.

def get_this(text):
    left, _, right = text.rpartition("-")
    return right.strip()


data = "- i don't want this - I do want this"
result = get_this(data)
print(result)