Home > front end >  In regex, how to look for a pattern with right-after constraint?
In regex, how to look for a pattern with right-after constraint?

Time:12-31

Assume that I have a string and I would like to use regex to get a pattern such that

The pattern starts with # and end with any character, say c, so that the next character of c, which is right-after c, is # or >.

How can I do that?


Here is the regex formula I tried #.*(?=[#>]). But it does not work as expected. Let's do some experiments to see what I got

Case 1. If the string is # text1 # text2, then I got # text1. So ok here.

Case 2. If the string is # text1 > text2, then I got # text1. So ok as well.

Case 3. If the string is # text1 # text2 > text3, then I got a single string # text1 # text2, while what I am expecting here is two strings # text1 and # text2

So how can I fix it?

CodePudding user response:

It's sufficient to make your quantifier lazy, using .*? in place of .*:

#.*?(?=[#>])

Check the demo here.

Note: If your samples can be more complex than the ones proposed in your post, update it with handpicked corner samples.

  • Related