YoongKang Lim
YoongKang Lim

Reputation: 566

Regular Expression Negative Lookbehind and Lookahead

I am trying to capture the price from a string. However, I facing some difficulty in capturing the price group. Below are my sample data and my approach.

Sample

cash $450
012-6323735 
cash 450
500

Current Approach

I try using negative lookbehind and lookahead of "-" character

(?<!\-)(\d+)(?!\-)

Current Output

enter image description here

Do anyone have any idea to capture the price group?

Desired Output

cash $450 (True, Capture Group 450)

012-6323735 (False)

cash 450 (True, Capture Group 450)

500 (True, Capture Group 500)

Upvotes: 1

Views: 474

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

When you tell regex that the value before/after a string of digits must not be a dash, regex engine is happy to use one of the digits in a sequence to satisfy this requirement. For example, it says that 01 is followed by 2, which is not a dash, so 01 must be what you want to capture; obviously, this is not what you want.

One approach to fix this is to add anchors \b before and after the capturing group:

(?<!\-)\b(\d+)\b(?!\-)

Demo.

Upvotes: 2

Related Questions