user3245240
user3245240

Reputation: 255

Extract Clojure string up to colon

I have a string "Breakfast: eggs & bacon @ll day!" and I'd like to extract everything up to the colon. I'd like to get back just "Breakfast".

Thanks in advance!

Upvotes: 1

Views: 1164

Answers (3)

hwnd
hwnd

Reputation: 70750

Adam's answer is preferable for a task like this. If you want to use regular expression, you could use re-find.

> (re-find #"^[^:]+"  "Breakfast: eggs & bacon @ll day!")
Breakfast

The regular expression uses a negation class to match everything up until the colon. If the regex contains no parenthesized capturing groups, then on a match re-find returns the part of the string that matches.

Upvotes: 4

Adam
Adam

Reputation: 4683

Try using split to split the string on the colon, and then get the first element of the result.

(clojure.string/split "Breakfast: eggs & bacon @ll day" #":")

split is likely the best option for you rather than using a regex with capture groups. You can also split on any regex you'd like, so if you want to split on something more complex, that is an option.

Upvotes: 5

0xpentix
0xpentix

Reputation: 742

If you're new to Regex, I recommend txt2re.com. You can enter your string, and click on the part you'd like to pick out. txt2re will then generate a Regex for you Many languages are supported, e.g. direct Perl/PHP output to match the string.

It's interesting to see in what way a Regex changes if you select another part of your text. You can learn (simple) Regex applications there, by playing around with the tool.

Upvotes: 1

Related Questions