简体   繁体   English

正则表达式在两个下划线之间获取单词

[英]regex to get word between two undescores

I've a line like bla_bla**_**test**_1**023我有一行像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.并想提取_和任何下划线之间的单词,后跟数字_digit ,这是上面示例中的test

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我尝试了以下正则表达式,但不幸的是不起作用: [^_ ]+(?=[ _\\d]) - 它让我得到“_digit”之前的所有单词,而不仅仅是_digit之前的_digit

This should work for you.这应该对你有用。 Use Pattern and Matcher with look-arounds .使用PatternMatcher进行环视

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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