如何在 java 中使用正则表达式提取最后一个最短的字符串
How can i extract last shortest string using regex in java
如何提取下面的粗体范围字符串
string :
- hello world blah -d blah vlaah -n blah vlahh
- hello world blah -n blah vlahh -d blah vlaah
- hello world blah -d blaaah
我试过了。 -[dn] .*$
但它找到了最长的匹配字符串,如下所示
- hello world blah -d blah vlaah -n blah vlahh
我想提取最短的匹配字符串。提前致谢
您可以使用 negative lookahead 来避免匹配另一个 -d/-n
:
-[dn] (?!.*?-[dn]).*$
可以在吃完之前扔一个greedy .*
:
^.*(-[dn] .*)$
并获取第一个 capture group. See test at regex101
的比赛
如何提取下面的粗体范围字符串
string :
- hello world blah -d blah vlaah -n blah vlahh
- hello world blah -n blah vlahh -d blah vlaah
- hello world blah -d blaaah
我试过了。 -[dn] .*$
但它找到了最长的匹配字符串,如下所示
- hello world blah -d blah vlaah -n blah vlahh
我想提取最短的匹配字符串。提前致谢
您可以使用 negative lookahead 来避免匹配另一个 -d/-n
:
-[dn] (?!.*?-[dn]).*$
可以在吃完之前扔一个greedy .*
:
^.*(-[dn] .*)$
并获取第一个 capture group. See test at regex101
的比赛