Home > Back-end >  Get the first substring by regex match method
Get the first substring by regex match method

Time:09-29

I have the below string https://xxx.xxx/xxx-xxxx-xxxx-xxxxx-xxxx-zzz-zzzz

I have to match the substring https://xxx.xxx/xxx-xxxx-xxxx-xxxxx-xxxx-

Please help me to get it by regex match method

Thank you so much !!!

CodePudding user response:

Assuming that you want the only text before the word, which is before the last hyphen of the url, try this regex

. -(?=. -)

Output:

image

Regex101 Demo

tell me if its okay for you...

CodePudding user response:

You could try pattern:

^https:\/\/[^\/] \/(?:[^-] -){5}

Pattern explanation:

^ - match beginning of the string

https:\/\/ - match https:// literally

[^\/] - match one or more character other than /

\/ - match / literally

(?:...) - non-capturing group

[^-] - - match one or more of other character than - and then match - literally

{5} - match preceeding pattern 5 times

Regex demo

  • Related