Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In regex, how to look for a pattern with right-after constraint?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading