Home > Mobile >  REGEX expression to delete everything after the first comma and digits
REGEX expression to delete everything after the first comma and digits

Time:06-29

I want to remove everything after the first comma and delete the 4 digit number in the beginning.

for example i have " 2015 nissan, altima, tiger " i want it to become "nissan". What regex expression will do this?

CodePudding user response:

import re

s = "2015 nissan, altima, tiger2015 nissan, altima, tiger"
match = re.match(r"\d{4} (. ?),", s)

# Check if the given string matches the regex.
if match:
    make = match[1]

\d{4} matches the four digits. . ? matches basically any substring of length 1 or greater. The ? means it's lazy, which ensures it stops before the first comma. This is put in parenthesis so it becomes a capture group. This group can be accessed via match[1].

CodePudding user response:

The regex that work is \d{4}\s(\w*?)\,.*

That is 4 digits, then an space, then a word woth letter, then a comma, and something else

  • Related