Regex match last occurrence of substring among the same substrings in the string

66 views Asked by At

For example we have a string: asd/asd/asd/asd/1#s_

I need to match this part: /asd/1#s_ or asd/1#s_ How is it possible to do with plain regex?

I've tried negative lookahead like this But it didn't work

\/(?:.(?!\/))?(asd)(\/(([\W\d\w]){1,})|)$

it matches this '/asd/asd/asd/asd/asd/asd/1#s_' from this 'prefix/asd/asd/asd/asd/asd/asd/1#s_' and I need to match '/asd/1#s_' without all preceding /asd/'s

Match should work with plain regex Without any helper functions of any programming language https://regexr.com/ I use this site to check if regex matches or not

here's the possible strings:

prefix/asd/asd/asd/1#s
prefix/asd/asd/asd/1s#
prefix/asd/asd/asd/s1#
prefix/asd/asd/asd/s#1
prefix/asd/asd/asd/#1s
prefix/asd/asd/asd/#s1

and asd part could be replaced with any word like

prefix/a1sd/a1sd/a1sd/1#s
prefix/a1sd/a1sd/a1sd/1s#
...

So I need to match last repeating part with everything to the right And everything to the right could be character, not character, digit, in any order

A more complicated string example:

prefix/a1sd/a1sd/a1sd/1s#/ds/dsse/a1sd/22$$@!/123/321/asd

this should match that part:

/a1sd/22$$@!/123/321/asd
1

There are 1 answers

0
The fourth bird On

If you want the match only, you can use \K to reset the match buffer right before the parts that you want to match:

^.*\K/a\d?sd/\S+

The pattern will match

  • ^ Start of string
  • .* Match any char except a newline until end of the line
  • \K Forget what is matched until now
  • /a\d?sd/ match a, optional digits and sd between forward slashes
  • \S+ Match 1+ non whitespace chars

See a regex demo