CyKon
CyKon

Reputation: 153

REGEX - group - JAVA

I want to do the following with only ONE regex pattern. (I've got no access to program code, I can only insert a regex pattern) I've got the text as input, e.g.

1000 lemons, 2 apples.

For the case "lemons" I want automatically the number of them, for the case "apples" I want automatically the number of them.

With the regex pattern like

/\d+\s(apples)/

I would get the result

2 apples

But I want the result

2

with ONE regex pattern.

How can I do that?

Upvotes: 0

Views: 34

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626835

Since

I've got no access to program code, I can only insert a regex pattern

You need a positive lookahead-based regex (i.e. the part that should be checked for but discarded from the output must reside inside (?=....) construct):

\d+(?=\s*\w+)

or a bit more specific for your examples (if you need to match digits before specific words only)

\d+(?=\s*(?:apples?|lemons?))

See regex demo 1 and demo 2.

Since lookaheads do not consume text, the text they match is not present in the output you get.

To only search for the number of lemons use

\d+(?=\s*lemons?)

Note that ? makes the preceding character optional (matches 1 or 0 occurrences).

Upvotes: 1

Related Questions