0

I need to match a string with alphanumeric, underscores and dashes only followed by one or zero forward slash only.

These are valid:

aBc
ab-9/
a_C-c/
3-b-c

These are invalid:

aBc/xyz
1bc/x7z/
hello//
a-b_/89u/13P

I am trying this:

([a-zA-Z0-9-_]{1,})(?=\\?)

But it is not working. It is still matching, for example, this: a-b_/89u/

Please help

karlosuccess
  • 843
  • 1
  • 9
  • 25
  • Looks like you're looking for `^[a-zA-Z0-9-_]+(?=\/?$)`? – 41686d6564 stands w. Palestine Sep 11 '22 at 00:10
  • Note that you could also use `^[\w-]+(?=\/?$)`, but depending on your regex engine and/or options, `\w` might also match other Unicode alphanumeric characters (not just English/ASCII ones). – 41686d6564 stands w. Palestine Sep 11 '22 at 00:13
  • @41686d6564standsw.Palestine I rephrased the questions here: https://stackoverflow.com/questions/73676037/regex-to-match-urls-with-2-subdirectories-deep-only , please help me – karlosuccess Sep 11 '22 at 00:57
  • Why use a lookahead and inside backslash if you're looking for slash? How about [`^[\w-]+/?$`](https://regex101.com/r/C9nEds/1) and how is your rephrased question's regex related to this? What tool/lang are you using and what's the context? – bobble bubble Sep 11 '22 at 05:17

1 Answers1

1

Using a pattern like (?=\\?) the positive lookahead will always be true as the question mark makes it optional, so it will match one of more occurrences of [a-zA-Z0-9-_]

In this case you could use a capture group for the part that you want, and optionally match / at the end of the string.


If you don't want to match double hyphens and an optional / at the end:

^(\w+(?:-\w+)*)\/?$

Regex demo

With a lookahead:

^\w+(?:-\w+)*(?=\/?$)

Regex demo

Or If you want to allow mixing chars, you can write it as:

^[\w+-]+(?=\/?$)

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70