Reputation: 115
I need to extract all the words in a string before a specific character, in this example a colon (:).
For example:
String temp = "root/naming-will-look-like-this:1.0.0-SNAP";
From the string above I would like to return:
"root" "naming" "will" "look" "like" "this"
I'm not great at regular expressions, and I've come up with this so far.
\w+(?=:)
Which only returns me the one word directly preceding the colon ("this").
How can I retrieve all words before?
Thanks in advance.
Upvotes: 3
Views: 7843
Reputation: 48711
Using \G
anchor in addition to Java's character class intersection you are able to store words into first capturing group:
\G(\w+)[\W&&[^:]]*
This won't bypass multiple colons like inside below input string:
root/naming-will-look-like-this:1.0.0-SNAP:some-thing-else
Upvotes: 0
Reputation: 39457
Try this:
String s = "root/naming-will-look-like-this:1.0.0-SNAP";
s = s.replaceAll(":.*", "");
String[] arr = s.split("\\W+");
Upvotes: 1
Reputation: 784958
You can use a lookahead like this:
\w+(?=.*:)
\w+
will match all words and the lookahead (?=.*:)
asserts that we have a :
ahead.
Upvotes: 6