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, sayc, so that the next character ofc, which is right-afterc, 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?
>Solution :
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.