Shakiba Moshiri
Shakiba Moshiri

Reputation: 23864

how to match integers inside a single line string

Looking for a pattern in ECMAScript flavor to find all integers
positive, like +1,
negative like -1,
and implicit-positive like 1
inside a single line, like:

0 zero +1 2.2 1.1 -1 -1.1 one 1

and NOT multi-line, like:

0
zero
+1
1.1
etc, ...

Therefore, for this line, the pattern should match: (0 +1 -1 1)

0 zero +1 2.2 1.1 -1 -1.1 one 1
^      ^^         ^^          ^  

based on:

  1. ECMAScript
  2. repetition is okay, so 12346789 should be match
  3. if it is possible, without capturing group ()
  4. As efficient as possible

Example:
A stupid pattern like: (?:^\d+|(?!\d)[+-]?\d+(?!\.)|\d+$) can match 0 +1 -1 1
But it does not match 1 in a string like:

0 zero 1 two 2
^            ^  

Because of (?!\d) before + and - signs

Upvotes: 0

Views: 47

Answers (1)

Racil Hilan
Racil Hilan

Reputation: 25351

Try this

(?:^| )[+-]?\d+?(?= |$)

It does everything you want, except rejecting multiline. It is not possible to reject multiline in ECMAScript regex, but you can easily test for multiline and reject it before you check with the regex above using this simple regex:

[\n\r]+?

Note: you don't need to run this pattern globally; you can break at the first match (i.e. first line break), so don't use the g flag.

Upvotes: 1

Related Questions