如何简化下面的正则表达式?

问题描述 投票:0回答:1

我需要如下匹配字符串中的20个数字,然后进行文本替换:

    0.61    -0.60    0.06    0.46    1.07      0.    0.47    0.07    0.61    -176.
    1.53    1.15    -176    176    NA    .05    0.05    2.65    176.    1.32

在此字符串中,数字可能以多种格式存在,如下所示:

  • 不带小数点的正整数和负整数,例如
    176
    -176
  • 带小数点的正整数和负整数,例如
    176.
    -176.
  • 带有整数部分的正实数和负实数,例如
    1.76
    -1.76
    0.76
    -0.76
  • 没有整数部分的正实数和负实数,例如
    .76
    -.076
  • 部分缺失数字:
    NA

文本替换后,上面提到的字符串应该是这样的:

0.61,-0.60,0.06,0.46,1.07,0.,0.47,0.07,0.61,-176.,1.53,1.15,-176,176,NA,.05,0.05,2.65,176.,1.32

我使用正则表达式如下:

^\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\r\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)\s+(NA|-?\d*\.?\d*)$

为了方便阅读,我将上面提到的正则表达式拆解如下:

^                   # line begin
\s+(NA|-?\d*\.?\d*) # number 1
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*) # number 10
\r                  # enter
\s+(NA|-?\d*\.?\d*) # number 11
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*)
\s+(NA|-?\d*\.?\d*) # number 20
$                   # line end

然后我使用以下语句进行文本替换:

$1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20

我用记事本++中的替换功能完成了整个事情。

我的问题是,如何简化上面提到的用于匹配数字的正则表达式,同时确保我可以正确地进行文本替换?

regex simplify
1个回答
0
投票

也许使用 awk 将这些列拆分成可用的内容? :)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.