kimwz.kr
kimwz.kr

Reputation: 298

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

Upvotes: 3

Views: 103

Answers (2)

Jonny 5
Jonny 5

Reputation: 12389

Could throw a greedy .* before to eat up:

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

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

Upvotes: 2

anubhava
anubhava

Reputation: 785196

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

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

RegEx Demo

Upvotes: 5

Related Questions