1

I have this regular expression for javascript that should return a match when the string does not start or end with a forward slash (or both). The problem is that it does not return a match if I just type a single character (i.e. 'g').

https://regex101.com/r/9Bi3uc/1

The expression: (^[^/].*)(.*[^/]$)

Any idea what I am doing wrong?

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225

2 Answers2

0

I believe the reason it won't match single characters, is that you have two instances of [^/] in your regex. This means that it needs at least two characters that are not slashes for it to properly match. A quick solution to this is to use a regex OR operator to handle this case. Here's a modified version of your regex that matches all of your examples:

((^[^/].*[^/]$)|^[^/]$)

This can be broken into two segments

(^[^/].*[^/]$)

this first part is a shortened version of yours and will capture any strings with a length of 2 or more that don't start or end with a slash.

The second part on the other side of the OR operator (|) is this ^[^/]$

This will match a single character lines that are not a slash.

Jesse R
  • 61
  • 4
0

You can use

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

See the regex demo. If you need to also allow empty strings, you need to wrap the pattern with an optional non-capturing group:

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

See this regex demo.

Note that . does not always match any chars, make sure you use the right flag for the . to match line breaks as well, or use workarounds.

If you have a specific pattern to validate specific strings and you want to add the restrictions rgarding leading/trailing / chars, you can use lookarounds:

^(?!\/)your_pattern$(?<!\/)

This will match your pattern as a whole string while not allowing / char at the start, end or both.

Another note on / escaping:

  • In JavaScript regex, in character classes, you do not need to escape /: /[/]/ is valid
  • In string regex patterns, when you define the regex via a string literal, you do not need to escape /s (new RegExp("a/b/c"))
  • You can avoid escaping /s in case you can use another regex delimiter char (e.g. in PHP, "~a/b/c~")
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563