Jeferson Correa
Jeferson Correa

Reputation: 67

Regex to get string until "-" (if exists) and then remove 2 last characters

I need a regular expression to use in python that captures one group containing the whole string minus the last 2 characters, but if the string have a "-" , then ignore it and all after it.

Ex:

abcde = abc

jklmno-pqrs = jklm

I think it would be a mix between (.*)..$ and ^([^-]*) , but I dont know how to combine them.

Upvotes: 1

Views: 1453

Answers (2)

The fourth bird
The fourth bird

Reputation: 163287

You could use a capture group matching any char except - followed by matching 2 chars other than -

^([^-\n]+)[^-\n]{2}(?:-.*)?$

In parts, the pattern matches:

  • ^ Start of string
  • ([^-\n]+) Capture group 1, match 1 or more chars other than - (add \n to not match a newline)
  • [^-\n]{2} Match 2 chars other than -
  • (?:-.*)? Optionally match - followed by 0+ times any char
  • $ End of string

Regex demo

For example

import re
 
pattern = r"^([^-\n]+)[^-\n]{2}(?:-.*)?$"
s = ("abcde\n""jklmno-pqrs")
 
print(re.findall(pattern, s, re.M))

Output

['abc', 'jklm']

Upvotes: 3

Assad Ali
Assad Ali

Reputation: 288

You can combine two regex using pipe delimiter like this

re.findall('(.*)..$|^([^-]*)', string)

for reference '|' pipe delimiter is used for grouping multiple regular expressions

Upvotes: -1

Related Questions