正则表达式语句,匹配可选字符到同一组中。

huangapple go评论64阅读模式
英文:

Regex statement that matches an optional character into the same group

问题

正则表达式沙盒:

https://regex101.com/r/nAhuot/1

我需要将浮点数与整数分组。关键词是相同的组。我可以匹配小数点后的内容,如下所示:

(\d+)?(.)?(\d+)[ \t]+NUM(\d) <--- 用于匹配小数点后的正则表达式
(\d+)[ \t]+NUM(\d) <---- 用于匹配小数点之前的正则表达式

这是文本内容:

1.5707963267949         NUM0 ;
0                       NUM1 ;
0                       NUM2 ;
0                       NUM3 ;
0                       NUM4 ;
0                       NUM5 ;

期望的结果是在正则表达式内有2个组,看起来像这样:

(1.5707963267949,NUM0),(0,NUM1),(0,NUM2),(0,NUM3),(0,NUM4),(0,NUM5)

我的解决方案创建了多个组,如何将它们合并成一个组?

英文:

Regex sandbox:

https://regex101.com/r/nAhuot/1

I need to group floats with ints. The keyword here is the same group. I can match beyond the decimal point like so:

(\d+)?(.)?(\d+)[ \t]+NUM(\d) <--- Regex to match beyond the decimal
(\d+)[ \t]+NUM(\d) <---- Regex to match up to the decimal

This is the text:

1.5707963267949         NUM0 ;
0                       NUM1 ;
0                       NUM2 ;
0                       NUM3 ;
0                       NUM4 ;
0                       NUM5 ;

The expected result is to have 2 groups within the regex, look like this:

(1.5707963267949,NUM0),(0,NUM1),(0,NUM2),(0,NUM3),(0,NUM4),(0,NUM5)

My solution makes multiple groups, how can I make it to group into only one group?

答案1

得分: 1

不确定为什么答案从评论中删除了,但这是有效的代码:

((?:\-)?\d+(?:\.\d+)?)[ \t]+NUM(\d+)

感谢解决问题的用户,但已遗失他的用户名。

英文:

Unsure why the answer was wiped from the comments, but this is what worked:

((?:\-)?\d+(?:\.\d+)?)[ \t]+NUM(\d+)

Thank you to the user who solved it, lost his username

huangapple
  • 本文由 发表于 2023年6月1日 03:10:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定