regex to get word between two undescores

偶尔善良 提交于 2021-01-28 20:19:49

问题


I've a line like bla_bla**_**test**_1**023

and would like to extract the word between _ and any underscore followed by digit _digit which is test in the above example.

I've tried the following regex but unfortunately does not work: [^_ ]+(?=[ _\d]) - it getting me all words before "_digit" not only the one which is before _digit


回答1:


This should work for you. Use Pattern and Matcher with look-arounds.

public static void main(String[] args) {
    String word= "bla_bla_test_1023";
    Pattern p = Pattern.compile("(?<=_)([^_]+)(?=_\\d+)");
    Matcher m = p.matcher(word);
    while (m.find()) {
        System.out.println(m.group());
    }


}

O/P :

test




回答2:


 [^_]*(?=_\d)

You want to match everything other than _ until you get to _ followed by a digit.



来源:https://stackoverflow.com/questions/53013824/regex-to-get-word-between-two-undescores

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