SSQs
SSQs

Reputation: 329

Regex to match numbers in a string

I have the following string from which i need to extract numbers and also "-"s.

51 Will-Ratelle 6 5 11 - 1.5-5 - 1-0 - - - -

I am using the regex below to extract numbers which works

(\+|-)?\d+(?:\.\d+)?

But this will give me only 51, 6, 5, 11, 1.5, -5, 1, -0

I want to extract "-"s also.

I tried few alternatives which reads "-" in the name "Will-Ratelle", which i want to skip.

Any help regarding this will be appreciated.

Upvotes: 1

Views: 766

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use

[+-]?\d+(?:\.\d+)?|\B-\B

See the regex demo

Explanation:

  • [+-]?\d+(?:\.\d+)? - matches float values with or without - or + sign (\d+ matches 1+ digits, and (?:\.\d+)? matches a dot followed with 1+ sigits 1 or 0 times (optionally))
  • | - or...
  • \B-\B - a standalone hyphen not standing right after or before a word (\B is a non-word boundary).

Upvotes: 2

Related Questions