How can I extract the last shortest string using regex in java

how can i extract the selected range row below

line:

  • hello world blah -d blah vlaah -n blah vlahh
  • hello world blah -n blah vlahh -d blah vlaah
  • hello world blah -d blaaah

I tried. -[dn] .*$

but it found the longest match string as shown below

  • hello world blah -d blah vlaah -n blah vlahh

I want to extract the shortest match string. thank you in advance

+3


source to share


2 answers


You can use negative lookahead to avoid matching another -d/-n

in a match:

-[dn] (?!.*?-[dn]).*$

      



Demo version of RegEx

+5


source


Perhaps before eating: greedy .*

:

^.*(-[dn] .*)$

      



And take the matches of the first group. See test in regex101

+2


source







All Articles