匹配由空格分隔的表达式

时间:2016-05-24 16:55:39

标签: regex numbers

我有以下一行:

1 2/5 0.4 1+3i

每个组可以用一个或多个空格分隔。第一个,在他之前可以有空格。最后一个可以在他之后有空格。

我想得到:

1
2/5
0.4
1+3i

如何使用正则表达式获取它们? 简单来说,我尝试了一个较短的例子,因为复杂性更难:

2 3i

我尝试使用以下正则表达式:

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

但我将i与其整数分开:

2
3
i

我无法为我的问题找到一个好的正则表达式。任何解决方案?

1 个答案:

答案 0 :(得分:2)

您可以使用match代替

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

正则表达式细分

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

进一步细分

(
   (?:\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

相关问题