Home > Enterprise >  Extracting text from a string after 5 characters and without the last slash
Extracting text from a string after 5 characters and without the last slash

Time:10-23

I have a few strings:

some-text-123123#####abcdefg/
some-STRING-413123#####qwer123t/
some-STRING-413123#####456zxcv/

I would like to receive:

abcdefg
qwer123t
456zxcv

I have tried regexp:

/[^#####]*[^\/]/

But this not working...

CodePudding user response:

To get whatever comes after five #s and before the last /, you can use

/#####(.*)\//

and pick up the first group.

Demo:

const regex = /#####(.*)\//;

console.log('some-text-123123#####abcdefg/'.match(regex)[1]);
console.log('some-STRING-413123#####qwer123t/'.match(regex)[1]);
console.log('some-STRING-413123#####456zxcv/'.match(regex)[1]);

CodePudding user response:

assumptions:

  • the desired part of the string sample will always:
    • start after 5 #'s
    • end before a single /

suggestion: /(?<=#{5})\w*(?=\/)/

So (?<=#{5}) is a lookbehind assertion which will check to see if any matching string has the provided assertion immediately behind it (in this case, 5 #'s).

(?=\/) is a lookahead assertion, which will check ahead of a matching string segment to see if it matches the provided assertion (in this case, a single /).

The actual text the regex will return as a match is \w*, consisting of a character class and a quantifier. The character class \w matches any alphanumeric character ([A-Za-z0-9_]). The * quantifier matches the preceding item 0 or more times.

successful matches:

  • 'some-text-123123#####abcdefg/'
  • 'some-STRING-413123#####qwer123t/'
  • 'some-STRING-413123#####456zxcv/'

I would highly recommend learning Regular Expressions in-depth, as it's a very powerful tool when fully utilised.

MDN, as with most things web-dev, is a fantastic resource for regex. Everything from my answer here can be learned on MDN's Regular expression syntax cheatsheet.

Also, an interactive tool can be very helpful when putting together a complex regular expression. Regex 101 is typically what I use, but there are many similar web-tools online that can be found from a google search.

  • Related