1

I have the following line:

1 2/5 0.4 1+3i

Each group can be separated by one or more spaces. The first one, can have spaces or not before him. The last one can have spaces or not after him.

I want to get:

1
2/5
0.4
1+3i

How can I get them with regex? To be simple I tried on a shorter example because complex is the more difficult:

2 3i

I tried with the following regex:

/\s*((?:[\d]+)|(?:[\d]*\i))/g

But I get the i separated from its integer:

2
3
i

I can't find a good regex for my problem. Any solution?

Sylvain M
  • 131
  • 1
  • 7

1 Answers1

2

You can use match instead of split like

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

Regex Breakdown

((?:\d+(?:\.\d+)?)\/(?:\d+(?:\.\d+)?)) #For fractional part
  |
((?:[+-]?\d+(?:\.\d+)?)?[+-]?(?:\d+(?:\.\d+)?)?i) #For complex number
  |
([+-]?\d+(?:\.\d+)?) #For any numbers

Further Breakdown

(
   (?:\d+(?:\.\d+)?) #Match any number with or without decimal
     \/ #Match / literally
   (?:\d+(?:\.\d+)?) #Match any number with or without decimal
) #For fractional part

| #Alternation(OR)

(
   (?:[+-]?\d+(?:\.\d+)?) #Match real part of the number
   ? #This makes real part optional
   [+-]? #Match + or - and make it optional for cases like \di
   (?:\d+(?:\.\d+)?)? #Match the digits of imaginary part (optional if we want to match only i)
   i #Match i
) #For complex number

| #Alternation(OR)

([+-]?\d+(?:\.\d+)?) #Match any numbers with or without decimal

Regex Demo

rock321987
  • 10,942
  • 1
  • 30
  • 43