Sam
Sam

Reputation: 15761

Regular Expression Match - Javascript

I am trying to write a RegEx that will match this:

/Admin/doctemplate/edit/-537743660332489375

And the id number at the end can change. Also a separate RegEx to match like so:

/Admin/doctemplate/-537743660332489375/edit

I have tried:

/Admin/doctemplate/edit/[-0-9]+/

Upvotes: 1

Views: 43

Answers (2)

Kent
Kent

Reputation: 195029

here is the regex for both cases:

/^\/Admin\/doctemplate\/(edit\/-?\d+|-?\d+\/edit)$/

with your two example:

/^\/Admin\/doctemplate\/(edit\/-?\d+|-?\d+\/edit)$/.test(yourString1) ->true
/^\/Admin\/doctemplate\/(edit\/-?\d+|-?\d+\/edit)$/.test(yourString2) ->true

if you want to use the test multiple times, better make it as a variable:

var re= new RegExp("^/Admin/doctemplate/(edit/-?\d+|-?\d+/edit)$")
re.test(...)

Upvotes: 2

willlma
willlma

Reputation: 7533

You need to escape the forward slashes. Then you can use the digit class \d for the numbers ([-0-9]+ would also match 0-4-6-58---458, which I don't think you want).
1. \/Admin\/doctemplate\/edit\/-\d+
2. \/Admin\/doctemplate\/-\d+\/edit

I highly recommend regexr for messing with regex.

Upvotes: 2

Related Questions