简体   繁体   English

正则表达式强制和可选组

[英]Regex Mandatory and Optional Groups

I'd like to create a regex with groups which must be included in the string and groups which are only optional. 我想创建一个带有组的正则表达式,这些组必须包含在字符串和组中,这些组只是可选的。 I'm using c# for that. 我正在使用c#。

My Target String looks like this 我的目标字符串看起来像这样

    ##my_first_string-2#E+1##
    ##my_second_string-2#E-2##
    ##my_third_string__##

I have the following requirements : 我有以下要求

  • ## is mandatory at the beginning and the end (but this is not necessarily the beginning or end of line) ##在开头和结尾都是必需的(但这不一定是行的开头或结尾)
  • the string between ## and # (or ## ) is mandatory as well ## (或## )之间的字符串也是必需的
  • E+{Numbers} or E-{Numbers} is optional E + {Numbers}或E- {Numbers}是可选的

So far i have come up with 到目前为止,我已经提出了

(##.*?##)

=> to match all Characters in between the 2 ## ## =>匹配2 ## ##之间的所有字符

(##)([A-Za-z\-])\w+(##)

=> to match the first string. =>匹配第一个字符串。 But for some reason this captures ##my_first_string-2 and not only my_first_string-2 但由于某种原因,这会捕获## my_first_string-2而不仅仅是my_first_string-2

Could you help me create a regex for my requirements? 你能帮我创建一个符合我要求的正则表达式吗?

Try this: 尝试这个:

##([^#]+?)(#E[+-][0-9]+)?##

The important part is: 重要的是:

(#E[+-][0-9]+)?

The "?" “?” quantifier specifies zero or one occurrence 量词指定零或一次出现

Replace the following with the character requirements for the string, currently its just "all except #" 将以下内容替换为字符串的字符要求,目前只是“除#以外的全部”

([^#]+?)

Hope this helps. 希望这可以帮助。

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

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