Even if the shorter, similar string was after the longer string, the same Regular Expression (Regex) can be used to get the same result:- Input abcdefghijklmnopqrstuvwx abc Output abcdefghijklmnopqrstuvwx ABC Explanation: The abc.*xyz preceding the (SKIP)(*F) in the Regex helps skip the long string starting with abc and ending with xyz and matches the other abc in the shorter, similar string! In the Regex, the abc after the (SKIP)(*F) is matched.