简体   繁体   中英

Regex match only if string doesn't contain another string (Ruby gsub)

I am trying to match only a single / and change it to \\ / using gsub . How can I match only one / without matching the other ones?

Sample String:

"/* something */   example/123 anotherexample123/456  url/link/to/somewhere  "  

Expected Result:

"/* something */   example\ /123 anotherexample123\ /456  url/link/to/somewhere  "

Requirements:

  • Trying to avoid matching comments /* example */ .
  • Trying to avoid matching urls.
  • Only match singular words that contain a / .

Thoughts:

  • Don't match so that if the captured group begins and starts with a /
  • Match if it is a singular /
  • /(\\/)(.*)(\\/)/ matches all the pairs of / / that I DON'T want and could be a starting point

Use http://rubular.com/ to test

you could use this pattern

(?<!\/)\b([^\/ ]+)\/([^\/ ]+)\b(?!\/)

and replace with

$1\\ \/$2

Demo

#    (?<!\/)\b([^\/ ]+)\/([^\/ ]+)\b(?!\/)
(?<!            # Negative Look-Behind
  \/            # "/"
)               # End of Negative Look-Behind
\b              # <word boundary>
(               # Capturing Group (1)
  [^\/ ]        # Character not in [\/ ] Character Class
  +             # (one or more)(greedy)
)               # End of Capturing Group (1)
\/              # "/"
(               # Capturing Group (2)
  [^\/ ]        # Character not in [\/ ] Character Class
  +             # (one or more)(greedy)
)               # End of Capturing Group (2)
\b              # <word boundary>
(?!             # Negative Look-Ahead
  \/            # "/"
)               # End of Negative Look-Ahead

I'd do an assumption and say you only want to match / if they are within a sentence and used instead of space like the example you provided above : example1/l123

you could use this pattern to match them:

"(?<=\w{1,})/(?=w{1,})"

while

(?<=            # Positive Look-Behind
\w{1,}         # Match up to one of [a-z], [A-Z] and [1-9]
\              # match \
(?=            # Positive look-Ahead
\w{1,}         # Match up to one of [a-z], [A-Z] and [1-9]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM