ggRekt
ggRekt

Reputation: 33

Regex Ignore First 6 Matches Of Character

This is my string: /my/name/is/the/following/string/name.lastname/file.txt

I want to extract name.lastname from this string.

I've tried using \/.*\.app, but this selects: /my/name/is/the/following/string/name.lastname

How can I ignore the first 6 or 7 /'s?

Upvotes: 3

Views: 274

Answers (5)

((\/)[a-b]*).[^\/]{12}

Hi, Please try the above Reg ex, it should return what you expecting

Upvotes: 1

K.Dᴀᴠɪs
K.Dᴀᴠɪs

Reputation: 10139

You have quite a few good answers going for you. Here's one that uses positive look ahead (?=), with the end of string $.

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

The benefit here is you can have as many folders prior to your last folder, and it will still work.

DEMO

If we break this down, you have a

  • capturing group: ([^\/]+), and a
  • positive look ahead (?=\/[^\/]+$).

The capturing group will match everything except ^ a forward slash /, one to as many times possible +. This would actually capture every string between a forward slash, so that's why we use the positive lookahead.

The biggest factor in your positive lookahead is that it looks for the end of your string $ (signified by the dollar sign). It will look for everything after a forward slash / (hence the (?=\/ portion), then it will ensure no other forward slashes exists but match all other characters [^\/] one to unlimited times + to the end of the string $.

Upvotes: 3

AssenKhan
AssenKhan

Reputation: 566

try this ,it will match 6 or 7 th position

([a-z\.]*)(?=\/[a-z]*\.txt)

(?=\/[a-z]*\.txt) to check ends with .txt
([a-z\.]*) CapturingGroup to capture the name

Demo

Upvotes: 1

Valdi_Bo
Valdi_Bo

Reputation: 30971

If you want a more flexible solution, i.e. the string between last 2 slashes (not necessarily 6th and 7th), you can use:

\/([^\/]+)\/(?!.*\/)

Meaning:

  • \/ - A slash.
  • ([^\/]+) - Capturing group No 1 - a sequence of chars other than a slash. This is what you actually want to match.
  • \/ - Another slash.
  • (?! - Negative lookahead for:
  • .*\/ - a sequence of any chars and a slash.
  • ) - End of negative lookahead (works even in JavaScript version of Regex).

The above negative lookahead actually means: Nowhere further can occur any slash.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520978

You may use a repeating pattern to consume, but not match, the first six components of the path:

(?:\/[^\/]+){6}\/([^\/]+)

Your item will be available in the first capture group.

Demo

Upvotes: 1

Related Questions