Reputation: 1
I'm new to all this, so apologies for any inaccuracies.
I'm trying to write a regex that looks for "/" in a line at a specific position. If it is found, it should ignore everything before and match everything after.
So far, I've come up with
^(?(?=^.{6}[\/])[a-zA-Z0-9\_\-]+|\n)
but it seems to be doing the exact opposite; if "/" is found at the 7. position, it matches everything before "/". I got inspired by different threads, yet I'm still unable to make it work.
Any thoughts on what am I doing wrong?
Upvotes: 0
Views: 487
Reputation: 163632
The pattern ^(?(?=^.{6}[\/])[a-zA-Z0-9\_\-]+|\n)
uses an if clause, where in the if part there is an assertion for 6 characters followed by a /
The assertion is at the start of the string, and does not consume characters. If that assertion is true, then match either [a-zA-Z0-9\_\-]+
or a newline, so the consuming parts starts there and that is why you get that match.
It matches the first 6 characters and not the /
because that is not in the character class.
You can use a capture group to match all allowed characters after the /
at the 7th position.
^.{6}\/([a-zA-Z0-9_-]*)
^
Start of string.{6}\/
Match 6 characters and /
([a-zA-Z0-9_-]*)
Capture group 1, optionally match any of the listed in the character classOr if supported you can use \K
to forget what is matched so far:
^.{6}\/\K[a-zA-Z0-9_-]*
^
Start of string.{6}\/
Match 6 characters and /
\K
Clear the match buffer (forget what is matched until now)[a-zA-Z0-9_-]*
Optionally match any of the listed in the character classUpvotes: 3