Regex for matching all words before a specific character

亡梦爱人 提交于 2021-02-19 04:57:06

问题


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.


回答1:


You can use a lookahead like this:

\w+(?=.*:)

RegEx Demo

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




回答2:


Try this:

    String s = "root/naming-will-look-like-this:1.0.0-SNAP";
    s = s.replaceAll(":.*", "");
    String[] arr = s.split("\\W+");



回答3:


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


来源:https://stackoverflow.com/questions/41510839/regex-for-matching-all-words-before-a-specific-character

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!