Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python re match exact only one occurrence (no repeat Consecutive)

i want a python re to match exact one occurrence of / . indeed if occurs more / such as // or /// re shouldn't match any of them.

for example below inputs must convert:

a/b -> a b

a//b -> a//b

a/// -> a///b

like image 233
mmsamiei Avatar asked Oct 23 '25 01:10

mmsamiei


2 Answers

You need (negative) lookarounds:

(?<!\/)\/(?!\/)

Demo

This regex matches a single forward slash, but only if it's not preceeded or followed by another slash.

like image 79
L3viathan Avatar answered Oct 24 '25 13:10

L3viathan


You may use a regex with 2 capture groups:

r'^([^/]*)/([^/]*)$'

RegEx Demo

This regex:

  • ^: Start
  • ([^/]*): matches 0 or more characters that are not / and captures in group #1
  • /: Match a /
  • ([^/]*): matches 0 or more characters that are not / and captures in group #2
  • $: End

Code:

import re
str = re.sub(r'^([^/]*)/([^/]*)$', r'\1 \2', str)
like image 33
anubhava Avatar answered Oct 24 '25 15:10

anubhava



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!