-1

I'm trying to figure out how to extract usernames from a URL that's captured in a form. I do have the below regex, but the issue is that the second forward slash may not exist. Here are the examples:

Sample URLs
https://test.site.com/u/username
https://test.site.com/u/username/pref/summary

I'm trying to extract the username.

Current Regex
/u/(.*?)/

The current one I have above successfully extracts the username, but only when there is another / after the username. The second / needs to be optional; it may or may not be there, and there may or may not be more after that.

I just couldn't find the correct regex to make the second / optional (using ? at the end didn't help) but not exactly "optional," if that makes sense.

Thanks in advance!

BearsBeetsBSG
  • 55
  • 1
  • 9

1 Answers1

2

/u/([^/]*) will match as many non-/ characters after /u/ as possible.

It will not match pref and summary, because [^/] matches any character other than /, so [^/]* matches a string (as long as possible) of characters other than /.  Consider: if your pattern is B[aeiou]* and your input is Beetles (or Beethoven), it will match only Bee, stopping at (before) the first character that isn’t a vowel.  Similarly, [^/]* stops at (before) the first occurrence of /.