0

Is it possible to create a regex that only evaluates the first n number of characters in a string?

For example, given the strings:

Line 1: The quick brown fox jumped over the lazy dog.
Line 2: There was another fox that was not so quick.

I need a regex that only searches for the word quick within the first 15 characters. Such that line1 would match, but line2 would not match.

I'm interested in a single regex without combining with other commands, such as cut -c1-15, or something similar.

I understand that regex 'lookarounds' might be a possible solution, but can't seem to find anything that allows referencing position from the start of the input string.

1 Answer 1

2

You can quantify (with a range) a "dot anything" wildcard token and anchor the pattern to start of string to achieve this:

^.{1,15}quick

regex 101 demo

Sign up to request clarification or add additional context in comments.

4 Comments

but the regex fail when quick place start of the string.
yeah it would be {0,14} technically
I made your answer the accepted one. We can substitute the value to be whatever is required. Thank you.
One more followup...this solution technically provides a match no further away from the front than n characters. Not within the first n characters. But the numbers can be adjusted to achieve the desired effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.