I know I can exclude outside characters in a string using look-ahead and look-behind, but I’m not sure about characters in the center.
What I want is to get a match of ABCDEF from the string ABC 123 DEF.
Is this possible with a Regex string? If not, can it be accomplished another way?
EDIT
For more clarification, in the example above I can use the regex string /ABC.*?DEF/ to sort of get what I want, but this includes everything matched by .*?. What I want is to match with something like ABC(match whatever, but then throw it out)DEF resulting in one single match of ABCDEF.
As another example, I can do the following (in sudo-code and regex):
string myStr = "ABC 123 DEF";
string tempMatch = RegexMatch(myStr, "(?<=ABC).*?(?=DEF)"); //Returns " 123 "
string FinalString = myStr.Replace(tempMatch, ""); //Returns "ABCDEF". This is what I want
Again, is there a way to do this with a single regex string?
Since the regex replace feature in most languages does not change the string it operates on (but produces a new one), you can do it as a one-liner in most languages. Firstly, you match everything, capturing the desired parts:
(Make sure to use the single-line/”dotall” option if your input contains line breaks!)
And then you replace this with:
That will give you
ABCDEFin one assignment.Still, as outlined in the comments and in Mark’s answer, the engine does match the stuff in between
ABCandDEF. It’s only the replacement convenience function that throws it out. But that is supported in pretty much every language, I would say.Important: this approach will of course only work if your input string contains the desired pattern only once (assuming
ABCandDEFare actually variable).Example implementation in PHP:
Or JavaScript (which does not have single-line mode):
Or C#: