Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i extract last shortest string using regex in java

how can i extract bold range string in below

string :

  1. hello world blah -d blah vlaah -n blah vlahh
  2. hello world blah -n blah vlahh -d blah vlaah
  3. hello world blah -d blaaah

I tried. -[dn] .*$ but it found longest match string like below

  1. hello world blah -d blah vlaah -n blah vlahh

I want to extract shortest match string . thanks in advance

like image 622
kimwz.kr Avatar asked Jul 02 '26 19:07

kimwz.kr


2 Answers

You can use a negative lookahead to avoid matching another -d/-n in the match:

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

RegEx Demo

like image 152
anubhava Avatar answered Jul 04 '26 08:07

anubhava


Could throw a greedy .* before to eat up:

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

And grab matches of the first capture group. See test at regex101

like image 42
Jonny 5 Avatar answered Jul 04 '26 09:07

Jonny 5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!