Reputation: 580
Is it possible to use regex to search from end of string to beginning?
for example i have a string: "a2bba2b"
I know i need the last occurrence of /a2/ and it seems highly inefficient to make machine go trough whole string which can be quite long. I know the needle will be somewhere near the end of string(haystack), so i would like to reverse the order simply tell the script to search from end to beginning to save some resources. Regex seems like a way to go match more complicated string.And it is way easier to write complex regex than your own search function.
So is there a way maybe a flag or something to reverse searching order to match regex from end to start of input string. Does any of the modern languages support something like that? if not why?
Upvotes: 3
Views: 3667
Reputation: 626689
No, JavaScript RegExp does not allow searching from the end of the string. The usual workaround is using a greedy dot matching pattern to make the engine grab the whole string and then backtrack to find the last occurrence (as /.*a\d/
), but it will become a pain if a large string does not really contain this pattern.
If the purpose is to extract the last match, you may get all matches and grab the last one (s.match(/a\d/g).pop()
(well, there must be a null check, of course)).
There are regex engines that actually let you parse the string from right to left.
RegexOptions.RightToLeft
modifier for this (see the regex demo)regex.R
(or inline (?r)
version) to force a reverse matching: regex.compile(r'a\d', regex.R).sub(r"**\g<0>**", "a2bba2b", count=1)
==> a2bb**a2**b
) (see RexTester demo).Upvotes: 2
Reputation: 348
How about string reverse your string and your regex? then get the first occurence?
Upvotes: 0