Turn on / off greed in clojure repeat patterns

How to enable / disable greed in clojure repeat patterns?

(re-find #"(.+)-(.+)" "hello-world-you") => ["hello-world-you" "hello-world" "you"]

against

(re-find #"(.+)-(.+)" "hello-world-you") => ["hello-world-you" "hello" "world-you"]
+5
source share
2 answers

?makes quantifiers such as +non-greedy. By default, they are greedy.

  • Greedy: (.+)
  • Unwanted: (.+?)

By the way, this is just a direct, simple and accurate answer. @Fge's answer offers a better way to do this. Check it out for future expressions.

+15
source

Do not use .+, use the extended character class: this avoids worries about greed in general.

You should use this as a regular expression ([^-]+)-([^-]+).

, . , , (([^-]+)), (-), () , , (([^-]+)).

, () , , , . ( ), .

+12

All Articles