简体   繁体   English

C#RegEx匹配特定的字符串

[英]C# RegEx to match specific strings

I need to match (using regex) strings that can be like this: 我需要匹配(使用正则表达式)字符串,如下所示:

required: custodian_{number 1 - 9}_{fieldType either txt or ssn} optional: _{fieldLength 1-999} 必需:custodian_ {number 1-9} _ {fieldType txt或ssn}可选:_ {fieldLength 1-999}

So for example: custodian_1_ssn_1 is valid custodian_1_ssn_1_255 is valid 因此,例如:custodian_1_ssn_1有效custodian_1_ssn_1_255有效

custodian or custodian_ or custodian_1 or custodian_1_ or custodian_1_ssn or custodian_1_ssn_ or custodian_1_ssn_1_ are not valid 保管人或保管人_或保管人_1或保管人_1_或保管人_1_ssn或保管人_1_ssn_或保管人_1_ssn_1_无效

Currently I am working with this: 目前,我正在与此:

(?:custodian|signer)_[1-9]?[0-9]_(?:txt|ssn)_[1-9][0-9]?(_[1-9]?[0-9]?[0-9]?)?

as my regex and my api is working to pick up: custodian_1_txt_1 custodian_1_ssn_1 custodian_1_txt_1_25 5 <---- not matching the last "5" 正则表达式和api正在工作:custodian_1_txt_1 custodian_1_ssn_1 custodian_1_txt_1_25 5 <----与最后一个“ 5”不匹配

any thoughts? 有什么想法吗?

You may use pattern: 您可以使用模式:

^custodian(?:_[a-z0-9]+)+$
  • ^ Assert position beginning of line. ^行首的位置。
  • custodian Match literal substring custodian . custodian匹配文字串custodian
  • (?:_[a-z0-9]+)+ Non capturing group. (?:_[a-z0-9]+)+非捕获组。 Multiple sequence of _ followed by alphanumerics. _多个序列,后跟字母数字。
  • $ Assert position end of line. $行尾位置。

You can check the correct matches here . 您可以在此处检查正确的匹配项。

Obviously you can modify the pattern to add substring signer in non capturing group as: 显然,您可以修改模式以在非捕获组中添加子字符串signer ,如下所示:

^(?:custodian|signer)(?:_[a-z0-9]+)+$ . ^(?:custodian|signer)(?:_[a-z0-9]+)+$

I suggest using \\d for numbers not yours and this is my code try it:- 我建议使用\\d而不是您的数字,这是我的代码尝试:-

(?:custodian|signer)_[1-9]?[0-9]_(?:txt|ssn)_[1-9][0-9]?(_[1-9]?\d*)?

I just added a \\d value to the end of your pattern to match all end digits before another match. 我只是在您的模式末尾添加了一个\\d值,以匹配所有匹配末尾的数字。

您可以使用锚点来声明字符串的开始^和结束$ ,对于最后一部分,至少使前1-9不是可选的,否则它将匹配并在末尾加下划线:

^(?:custodian|signer)_[1-9]?[0-9]_(?:txt|ssn)_[1-9][0-9]?(_[1-9][0-9]?[0-9]?)?$

If you're only interested in the last digits, this super generic regex will do: 如果您仅对最后一位数字感兴趣,那么此超级通用正则表达式将执行以下操作:

(?:.+)_(\d+)

If you do need to match the whole string, this worked: 如果确实需要匹配整个字符串,则可以这样做:

^(?:custodian|signer)_\d+_(?:txt|ssn)(?:_\d+)?_(\d+)$

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

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