Home > OS >  Regex to match string that does not contain slash
Regex to match string that does not contain slash

Time:09-21

I am trying to set up a route using vue-router in a web app using regex to match the pattern. The pattern I am looking to match is any string that contains alphanumeric characters (and underscore) without slashes. Here are some examples (the first slash is just to show the string after the domain e.g. example.com/):

/codestack
/demo45
/i_am_long

Strings that should not match would be:

/data/files.xml
/share/home.html
/demo45/photos

The only regex I came up with so far is:

path: '/:Username([a-zA-Z0-9] )'

That is not quite right because it matches all the characters except for the slash. Whereas I want to only match on the first set of alphanumeric characters (including underscore) before the first forward slash is encountered.

If a route contains a forward slash e.g. /data/files.xml then that should be a different regex route match. Therefore I also need a regex pattern to match the examples above containing slashes. Theoretically, they could contain any number of slashes e.g. /demo45/photos/holiday/2015/bahamas.

CodePudding user response:

For the first part, you can match 1 or more word characters which will also match an underscore.

The anchors ^ and $ assert the start and end of the string.

^\w $

For the second one, you can start the match with word characters followed by /

In case of more forward slashes you can optionally repeat the first pattern in a group.

The last part after the pattern can be 1 or more word characters with a optional part matching a dot and word characters.

^\w /(?:\w /)*\w (?:\.\w )?$

Regex demo

If you want to match any char except / you can use [^/]

^(?:[^/\s] /) [^/\s] $

Regex demo

  • Related