Page 1 of 1
[Solved] Find shortest text between strings
Posted: Mon Apr 17, 2017 3:05 pm
by Butch1
Hi!
I would like to search for (and replace) substrings like this:
a.*b
i.e. beginning with a, then any number of other characters, then THE FIRST occuring b.
Example:
a12345b6789b1234 > a12345b (not a12345b6789b).
Thank you in advance!
Re: A Search RegEx Problem
Posted: Mon Apr 17, 2017 3:19 pm
by RoryOF
Do you wish to discard all characters after the first "b"?
Re: A Search RegEx Problem
Posted: Mon Apr 17, 2017 3:25 pm
by Butch1
??? No! As described: I want to search for strings a.....b and replace them.
Re: A Search RegEx Problem
Posted: Mon Apr 17, 2017 3:56 pm
by keme
Regular expressions use "greedy" matching, so they will match the largest chunk they can.
You want a RegEx to "find 'a', then the first 'b' after a number of arbitrary characters". To put that into a RegEx is simplest when you partially invert the logic: "find a 'b' after a number of characters which are not 'b'."
In regex that would be
Re: A Search RegEx Problem
Posted: Mon Apr 17, 2017 4:40 pm
by Butch1
@keme:
Thank you very much!!!
Unfortunately my question was a reduced one: My real problem is to find the smallest chunk beginning with a string and ending with another string. Something like this:
abcStringAdefghStringBijklmnStringBopqrts
Result: StringAdefghStringB
Do you have a hint for this case too?
Butch
Re: A Search RegEx Problem
Posted: Mon Apr 17, 2017 5:08 pm
by karolus
Hallo
you need an non-greedy expression:
stringa.*?stringb
Re: A Search RegEx Problem
Posted: Mon Apr 17, 2017 5:18 pm
by Butch1
@karolus:
Hallelujah!
Thank you!!!
Re: A Search RegEx Problem
Posted: Mon Apr 17, 2017 8:16 pm
by keme
Great! I learned something. Thanks, Karolus.