0

i am aware of the fact that backreference ovverride values if the backtraking occurs and the ovverided output will be the new backreference.

but if i take this regex for example:

([abc]+).*\1

then for the string:"abc me bca"

the output is:"abc me bca"

can someone explain how is that possible because as per the steps:

-[abc] matches a from the input.

-because their is an quantifier + so it will repeate one or more 
time and again matches b and c.then stops at whitespace as it's 
not either 'a', 'b' or 'c'.

-.* eats all the input string after abc and further goes 
to \1(the backreference).

- .* will do backtracking as \1 fails and because .* i.e zero 
or more so it will through all the charecters and again the + 
of [abc]+ will do backtracking.

-in backtracking of [abc]+ it will be do until 'a' after 
removing 'b' and 'c' but still their is no match for 
\1 as bca.

so how the output came as "abc me bca"..?

0

1 Answer 1

1

First character is a and last character is a.So its a match.

What happens is abc is captured in group then compared with bca.it fails.

So engine backtracks by 1.Now ab will be compared to ca.It fails.So engine

will backtrack again.a is compared to last a and it passes.So finally engine

stores a in group as it satisfies the match criteria .Note \1 is what gets

stored in the first group.It is not a fixed value.See demo.

https://regex101.com/r/sJ9gM7/72

Sign up to request clarification or add additional context in comments.

4 Comments

can you you please explain the ([bca]+)\s*\w*\s*\1 regex for "abc me bca" giving "bc me bc" output.?how it is removing the first 'a'.?
@Deepak if a matches then \s*\w*\s* will not match.So engine matched bc .Now \s*\w*\s* will match with ` me `
after [bca]+ will match "abc", can't \s*\w*\s* can match " me "..and will fail for "bca" bcoz \1 has "abc"..?
@Deepak yes it will fail ,then engine will try the next possible combination.Whenever you say a* it can a,aa,aaa .So It will try possible combinations to get match by capturing maxinum using + then leaving 1 by 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.