Insoluble regular expressions

I mean the usual cheating sheet. It says:

{3,5} means 3,4,and 5

{3,5}? means 3,4,5 ungreedy +

what does ungreedy + indicate?

+6
source share
1 answer

Quanitifier {3,5}? means that he will first try to match 3 occurrences and then see if the rest of the expression matches. If the rest of the expression fails, he backs off and tries 4, and then finally 5.

The greedy version {3,5} will try matches in the reverse order - the longest first.

Note that greed does not affect string match. This only affects the order in which the engine searches and the contents of the captures, if there are capturing groups.

Here is an example showing the difference. Imagine you have aaaaabc string.

  • (a{3,5})(\w*) will capture aaaaa and bc . (rubular)
  • (a{3,5}?)(\w*) will capture aaa and aabc . (rubular)
+10
source

Source: https://habr.com/ru/post/916133/


All Articles