anurupr
anurupr

Reputation: 2344

How to match any text upto the last comma?

I am trying to match all the text in the following line

is a frozen account. To create / edit transactions against this account, you need role,

excluding the last comma using this regex

.*?[,]

but this gives the following matches

is a frozen account. To create / edit transactions against this account,

you need role,

What am I missing here?

Upvotes: 1

Views: 1702

Answers (3)

zx81
zx81

Reputation: 41848

Use this (see the regex demo):

.*(?<!,)

Explanation

  • The .* matches the whole string
  • The negative lookbehind (?<!,) asserts that what precedes is not a comma, forcing the engine to backtrack if needed

Upvotes: 1

Braj
Braj

Reputation: 46871

Try greedy way to match at most possible

.*,

I need to exclude the last comma from the match

Try with Positive Lookahead

.*(?=,)

DEMO

Upvotes: 4

anubhava
anubhava

Reputation: 785876

You can use this lookahead based regex to match text until last comma:

.*?,(?![^,]*,)

Upvotes: 0

Related Questions