karvai
karvai

Reputation: 1767

Expression to capture only 1 occurrence for a single character but multiple for others

I am trying to use the following regex to capture following values. This is for use in Java.

(\$|£|$|£)([ 0-9.]+)

Example values which I do want to be captured via above regex which works.

$100
$100.5
$100
$100.6
£200
£200.6

But the following as gets captured which is wrong. I only want to capture values when there
is only 1 dot in the text. Not multiples.

£200.15.
£200.6.6.6.6

Is there a way to select such that multiple periods doesn't count?

I can't do something like following cos that would affect the numbers too. Please advice.

(\$|£|$|£)([ 0-9.]{1})

Upvotes: 1

Views: 89

Answers (2)

Engel
Engel

Reputation: 39

You could try this

(\$|£|$|£)([0-9]+(?:\.[0-9]+)?)$

one or more digits followed by an optional dot and some digits and then the end of the string.

EDIT: some typos fixed

And it's not ok to delete the whole sentence obove, due to one word against my self. :(

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

(\$|£|$|£)(\d+(?:\.\d+)?)\b(?!\.)

See the regex demo.

In this regex, (\d+(?:\.\d+)?)\b(?!\.) matches

  • (\d+(?:\.\d+)?) - Group 1: one or more digits, then an optional occurrence of . and one or more digits
  • \b - a word boundary
  • (?!\.) - not immediately followed with a . char.

Another solution for Java (where the regex engine supports possessive quantifiers) will be

(\$|£|$|£)(\d++(?:\.\d+)?+)(?!\.)

See this regex demo. \d++ and (?:\.\d+)?+ contain ++ and ?+ possessive quantifiers that prevent backtracking into the quantified subpatterns.

In Java, do not forget to double the backslashes in the string literals:

String regex = "(\\$|£|$|£)(\\d++(?:\\.\\d+)?+)(?!\\.)";

Upvotes: 1

Related Questions