Cornel Verster
Cornel Verster

Reputation: 1781

Java Regex number extract with differing formats

I have a String that can display a number in one of a few formats:

Name ProductA Price R 3 250

Or

Name ProductA Price R 500

I don't know in which format the price will appear, so I want to look for both. I know the Regex for the first String would be:

\\bPrice\\sR\\s\\b*(\\d\\s\\d+)

And for the second it would be:

\\bPrice\\sR\\s\\b*(\\d+)

But how would Regex look that checks for both and captures the Price number?

Upvotes: 1

Views: 64

Answers (2)

revo
revo

Reputation: 48711

You could have an optional group for following digits (price in capturing group one):

\bPrice\sR\s(\d+(?:\s\d+)?)

String literal: \\bPrice\\sR\\s(\\d+(?:\\s\\d+)?)

Breakdown:

  • \bPrice\sR\s Match literal string Price R
  • ( Start of capturing group one
    • \d+ Match a sequence of digits
    • (?:\s\d+)? Match a group of digits preceding an space, if exist, non-capturing group
  • ) End of capturing group

Or use a positive lookbehind to have price in group 0:

(?<=\bPrice\sR\s)\d+(?:\s\d+)?

String literal: (?<=\\bPrice\\sR\\s)\\d+(?:\\s\\d+)?

Live demo

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

Make \\s\\d part optional, like this:

\\bPrice\\sR(?:\\s(\\d))?\\s(\\d+)
--          ^^^^^^^^^^^^^

Note that the optional part group is non-capturing, letting you retrieve the relevant portions of the price through capturing groups 1 and 2.

Demo.

Upvotes: 3

Related Questions