Voxoff
Voxoff

Reputation: 155

Regex lookaround

When all was simple we had a regex /[^A-Za-z0-9]/ Once matched, we would substitute in underscores

  American Football # American_Football
  Mini Golf         # Mini_Golf

However, we do not want it to match

  AR/ VR

I thought a neg lookbehind would work but alas...Why does the neg lookbehind not go back and make sure \/\s does not match?

 [^A-Za-z0-9](?<!\/\s)

Thanks

Upvotes: 2

Views: 85

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

[^A-Za-z0-9](?<!\/\s) matches / in AR/ VR because it is not a whitespace preceded with /, see this demo:

enter image description here

You seem to want to only match an non-alphanumeric character between alphanumeric characters:

/(?<=[A-Za-z0-9])\W(?=[A-Za-z0-9])/

See this regex demo.

Details

  • (?<=[A-Za-z0-9]) - right before, there must be an alphanumeric char
  • \W - a non-word char (non-alpha, non-underscore) char
  • (?=[A-Za-z0-9]) - right after, there must be an alphanumeric char.

Upvotes: 1

Related Questions