Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - how to match a line between two optional characters that are not included in group?

Tags:

python

regex

The regex should match

  • /exampleline - match exampleline
  • exampleline - match exampleline
  • exampleline/ - match exampleline
  • /exampleline/ - match exampleline

I tried ?\/(.+)\/? but it didn't work
/exampleline/ and exampleline/ matched exampleline/, instead of exampleline

like image 727
Platon Avatar asked Oct 26 '25 13:10

Platon


2 Answers

It is necessary to remove the symbol "/" from the group. Try this:

\/?([^\/]+)\/?
like image 124
satrezviy Avatar answered Oct 29 '25 03:10

satrezviy


You can match any character except /. Then optionally match a part that matches the whole line ending on a character other than /

[^/\n](?:.*[^/\n])?

The pattern matches:

  • [^/\n] Match a character other than a newline or /
  • (?: Non capture group to make the whole part optional
    • .* Match the whole line
    • [^/\n] Match a character other than a newline or /
  • )? Close the non capture group and make it optional

See a regex demo

If the match should start and end with a non whitespace character, you can replace the \n with \s

[^/\s](?:.*[^/\s])?

See another regex demo

like image 31
The fourth bird Avatar answered Oct 29 '25 02:10

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!