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

Regex: Replacing the first leftmost occurence or the first rightmost occurence

I need to create a regex that could modify something similar to the following string.

[[12][abad][32][@adb.]

So if I wanted to match with the leftmost occurrence of a, it’d mark the following.

[[12][*a*bad][32][@adb.]

Or if I matched with the rightmost occurrence of @ad, it’d mark the following:

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

 [[12][abad][32][*@ad*b.]

Ideally, I’d want the regex to be sort of like a function (i.e., given a substring and/or character, match with the first leftmost occurrence, or match with the first rightmost occurrence, of that input). I’d be able to pick any substring, and there’d be some static component in the regex that’s easily modifiable (making it act like a function).

I’ve seen some similar questions that mentioned lazy regex with *? to get the first match (for example, I saw a question that gave \[\#(.*?)\] as its answer), but I wasn’t sure how to integrate the answers given and make the function I mentioned above, that could take any string/character input and find its left-most or right-most occurrence.

>Solution :

If your regex tool/language support replacements with capture groups, then you may try (for the left most a):

Find:    ^([^a]*)a(.*)$
Replace: $1*a*$2

Demo

For the right most a use:

Find:    ^(.*)a(.*)$
Replace: $1*a*$2
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