Ask Your Question
4

How can one restrict regex from going back beyond a certain pattern?

asked 2023-05-21 05:01:01 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-21 05:06:01 +0000

plato gravatar image

One way to restrict regex from going back beyond a certain pattern is by using a positive lookahead assertion. For example, if you want to match a string that contains "foo" followed by "bar", but only if "foo" appears before "baz", you can use the following regex:

/foo(?=.*baz).*bar/

This regex uses a positive lookahead assertion (?=.*baz) to ensure that "baz" appears after "foo" in the string. This means that the regex engine will only start matching "bar" after it has matched "foo" and ensured that "baz" appears later in the string.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-21 05:01:01 +0000

Seen: 8 times

Last updated: May 21 '23