简体   繁体   English

为给定字符串生成 RegEx 模式

[英]Generating RegEx pattern for a given string

I need to generate a RegEx pattern for a file name validation.我需要为文件名验证生成一个 RegEx 模式。 But I am not used to RegEx pattern.但我不习惯 RegEx 模式。 I did try to generate patterns by using think link .我确实尝试使用 think link生成模式。 I generated a pattern (^.*$)|(^.*i.*$) but it is not working as desired and got new pattern ^\\d+(?:_[A-Za-z]+)?$ from an answer but some new conditions are required which I have listed below.我生成了一个模式(^.*$)|(^.*i.*$)但它没有按预期工作并且得到了新模式^\\d+(?:_[A-Za-z]+)?$从一个答案,但需要一些我在下面列出的新条件。

My required validations are as follows :我需要的验证如下:

  • 1234567890 => Valid 1234567890 => 有效
  • 1234567890_Alphabet => Valid, '_' symbol is valid, other symbol as well as white space characters are invalid. 1234567890_Alphabet => 有效,'_' 符号有效,其他符号以及空白字符无效。
  • 1234567890 - Alphabet => Invalid 1234567890 - 字母 => 无效
  • 1234567890alphabet => Invalid 1234567890alphabet => 无效

New conditions :新条件:

  • 11244422_134444_john => Valid 11244422_134444_john => 有效
  • 1234322_1234431 john => Invalid 1234322_1234431 约翰 => 无效
  • 1234222_134322-john => Invalid 1234222_134322-约翰 => 无效
  • 12422344_12453222 => Valid 12422344_12453222 => 有效

Some other validations :其他一些验证:

  • The string should start as numeric but not alphabet.字符串应以数字开头,而不是字母开头。 ie Numeric only即仅数字
  • Underscore(_) preceded by numbers.下划线 (_) 前面是数字。

Start by matching the digits, and optionally match an underscore and ASCII chars A-Za-z.首先匹配数字,并可选择匹配下划线和 ASCII 字符 A-Za-z。

^\d+(?:_\d+)?(?:_[A-Za-z]+)?$
  • ^ Start of string ^字符串开始
  • \\d+ Match 1+ digits \\d+匹配 1+ 个数字
  • (?:_\\d+)? Optionally match _ and 1+ digits可选匹配_和 1+ 位数字
  • (?:_[A-Za-z]+)? Optionally match _ and 1+ times any of A-Za-z可选匹配_和 1+ 次 A-Za-z
  • $ End of string $字符串结尾

Regex demo正则表达式演示

[0-9]+($|_[A-Za-z]+)

see https://regex101.com/r/X5BMJ1/1 for live example请参阅https://regex101.com/r/X5BMJ1/1以获取实时示例

Basically, you get numbers first, and that's it ($) or you require _ followed by letters基本上,你先得到数字,就是这样 ($) 或者你需要 _ 后跟字母

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

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