IrishCrf
IrishCrf

Reputation: 115

Regex for matching all words before a specific character

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

Answers (3)

revo
revo

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

Gurwinder Singh
Gurwinder Singh

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

anubhava
anubhava

Reputation: 784958

You can use a lookahead like this:

\w+(?=.*:)

RegEx Demo

\w+ will match all words and the lookahead (?=.*:) asserts that we have a : ahead.

Upvotes: 6

Related Questions