Python regex. How to exclude question mark from a string?

Viewed 301

I need to exclude a question mark from a string using the exclusion of that character, but I still get some undesired results. I have to get any link (as text) that doesn't have a question mark, for example, I have to exclude an URL like:

https://www.example.com/?var=yes

and get any other text (I've already selected which of them are HTTP links, I need those that have /l/ in the middle but without "?").

I tried:

re.compile("(/l/){1}[^\?]*")

or

re.compile("(/l/){1}[^\?]")

but I still get some texts with "?".

I'll appreciate any help!

2 Answers

Use

re.compile(r"^[^?]*/l/[^?]*$")

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  [^?]*                    any character except: '?' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  /l/                      '/l/'
--------------------------------------------------------------------------------
  [^?]*                    any character except: '?' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

You can use this pattern: ^(?!.*\?).*

See Regex Demo

Related