简体   繁体   English

匹配带有特殊字符的正则表达式

[英]Matching Regex with special characters repeated

have a test string . 有一个测试字符串。

  1. consists of 8 digits. 由8位数字组成。
  2. must have --- , - , . 必须有---- . or : separator such that string gets divided in parts, with each part having exactly two digits. :分隔符,以使字符串分成几部分,每部分恰好有两位数字。
  3. string must have exactly one kind of separator. 字符串必须完全具有一种分隔符。
  4. Separators must have integers on both sides 分隔符两边都必须有整数

i am not able to met 3rd condition 我无法满足第三条件

My answer : ^(\\d{2}(([-]{3})|.|:|-)){3}(\\d){2}$ 我的答案: ^(\\d{2}(([-]{3})|.|:|-)){3}(\\d){2}$

Example: 1. 11---11---11---11 2. 11:11:11:11 示例:1. 11---11---11---11 2. 11:11:11:11

Please help . 请帮忙 。

Note that the requirements translate to the string having the form ##:##:##:## , ie two numbers, following by separator, etc. 请注意,要求转换为格式为##:##:##:##的字符串,即两个数字,后跟分隔符等。

You can use patterns for each separator type along with an alternation to include all four separator types: 您可以为每种分隔符类型使用模式,并交替使用所有四种分隔符类型:

^(?:\d{2}---\d{2}---\d{2}---\d{2})|
 (?:\d{2}-\d{2}-\d{2}-\d{2})|
 (?:\d{2}\.\d{2}\.\d{2}\.\d{2})|
 (?:\d{2}:\d{2}:\d{2}:\d{2})$

I broke the regex up into multiple lines for readability. 我将正则表达式分成多行以提高可读性。

Demo here: 演示在这里:

Regex101 正则表达式101

This regex could be simplified to this: 此正则表达式可以简化为:

^(?:\d{2}---){3}\d{2}|(?:\d{2}-){3}\d{2}|(?:\d{2}:){3}\d{2}|(?:\d{2}\.){3}\d{2}$

But I actually prefer the longer open form because it is easier to read. 但是我实际上更喜欢较长的开放形式,因为它更易于阅读。

更简单的答案:^(?:\\ d {2}(-){3}){3} \\ d {2} |(?:\\ d {2}-){3} \\ d {2} |(? :\\ d {2}:){3} \\ d {2} |(?? \\ d {2}。){3} \\ d {2} $

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

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