问题
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