简体   繁体   English

正则表达式 C# - 中间的可选组

[英]Regex C# - optional group in the middle

I have such source text with an optional group in the middle:我有这样的源文本,中间有一个可选组:

GH22-O0-TFS-SFSD 00-1-006.19135
GH22-O0-TFS-SFSD 00-1-006.1.19135

Desired value in the first case will be '19135' and in the second '1.19135'.第一种情况下的期望值是“19135”,第二种情况是“1.19135”。

Regex has to match the whole string and select all characters after first "."正则表达式必须匹配整个字符串并选择第一个“。”之后的所有字符。 - which is my Group 1. I tried to make subgroups and mark Group 3 as optional but it is not working. - 这是我的第 1 组。我尝试创建子组并将第 3 组标记为可选,但它不起作用。

Regex:正则表达式:

.*\.0*(([0-9])(\.0*([0-9]+)))

How it should be changed to capture desired values?应该如何更改以捕获所需的值?

You can use您可以使用

^(.*?)\.0*(\d+)(?:\.0*(\d+))?$

See the regex demo .请参阅正则表达式演示 Details :详情

  • ^ - start of string ^ - 字符串的开始
  • (.*?) - Group 1: any zero or more chars other than an LF char as few as possoble (as *? is a lazy quantifier) (.*?) - 第 1 组:除 LF 字符之外的任何零个或多个字符(因为*?是一个惰性量词)
  • \\. - a dot - 一个点
  • 0* - zero or more zeros 0* - 零个或多个零
  • (\\d+) - Group 2: any one or more digits (\\d+) - 第 2 组:任何一位或多位数字
  • (?:\\.0*(\\d+))? - an optional occurrence of . - 的可选出现. , zero or more zeros, then Group 3 capturing one or more digits ,零个或多个零,然后第 3 组捕获一个或多个数字
  • $ - end of string. $ - 字符串的结尾。

I hope I understand your goals and this should work:我希望我理解你的目标,这应该有效:

.*?\.([\d.]+)
  • .*?\\. - loosely capture everything leading up to the first period - 松散地捕捉到第一个时期的一切
  • ([\\d.]+) - capture the remaining digits and periods into capture group #1 ([\\d.]+) - 将剩余的数字和句点捕获到捕获组 #1 中

https://regex101.com/r/0t9Ijy/1 https://regex101.com/r/0t9Ijy/1

This should work for you:这应该适合你:

.*?\.(.*)

This will match the whole string and include everything after the first period in capture group 1 regardless of character type.这将匹配整个字符串并包括捕获组 1 中第一个句点之后的所有内容,无论字符类型如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM