简体   繁体   中英

regex to get word between two undescores

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

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

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

您想匹配除 _ 以外的所有内容,直到找到 _ 后跟一个数字。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM