Bill Petrosino
Bill Petrosino

Reputation: 63

capturing values after an optional slash

I am trying to write in regex a string that allows me to have

I want to capture any group of at least 3, with our without a slash, and then anything after it.

And I am having a very hard time accomplishing this. If I require the slash / it is much easier to do so.

When I try

(?=.+\/?.+)[a-z0-9]{2,5}\/?(?<!3\/|3)

I can capture what I want - up until the slash, but can't crack how to get anything after IF legit things occur

(?=.+\/?.+)[a-z0-9]{2,62}\/?.?

My requirement for length goes up by 1 - to 4 instead of 3 - due to the additional . I put after the \/?. I could change my match to account for it, but it becomes really difficult.

(?=.+\/?.+)[a-z0-9]{2,5}\/?(?<!3\/|3)$

This only gives me the last slash or non slash follwed by 2,5 characters.

(?=.+\/?.+)[a-z0-9]{2,62}\/?.*

or

(?=.+\/?.+)[a-z0-9]{2,62}\/?.?+ 

simply then ignores my ending rule, of not being able to close with3/ or 3. Also this allows me to use more than 5 characters before the slash. Def not what I want :)

Is there a way to make an optional field still maintain length and ending rules?

I am running this script on both regexr.com and https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_regexp and gitbash and not getting the results I would like

Upvotes: 2

Views: 99

Answers (2)

The fourth bird
The fourth bird

Reputation: 163632

If the last character in this range [a-z0-9] should not be a 3 you can exclude it like [a-z124-9]

^[a-z0-9]{2,4}[a-z124-9](?:\/.*)?$

Explanation

  • ^ Start of string
  • [a-z0-9]{2,4} Match 2-4 chars in the ranges a-z 0-9
  • [a-z124-9] Match a single char a-z and then either 1,2 4-9
  • (?:\/.*)? Optionally match / and the rest of the line
  • $ End of string

See a regex101 demo.

If you can not match a 3 at all:

^[a-z124-9]{3,5}(?:\/.*)?$

See another regex101 demo

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195593

Try:

^[a-z0-9]{3,5}(?<!3)(?:$|\/.*)

Regex demo.


^ - beginning of the string

[a-z0-9]{3,5} - capture a-z0-9 between 3 and 5 times

(?<!3) - the last character should not be 3

(?:$|\/.*) - match either end of string $ or / and any number of characters.

Upvotes: 2

Related Questions