简体   繁体   English

正则表达式与模式匹配

[英]Regex matching with a pattern

I want to match a string pattern like below. 我想匹配如下字符串模式。

abcd;abcd;sdfdf;sdfdf;sdsdf; abcd; abcd; sdfdf; sdfdf; sdsdf;

  1. ';' ';' should appear at most 5 times.(or less) 最多应出现5次(或更少)。
  2. if 5th ';' 如果第5个';' is at the end no characters should be followed after that 最后,此后不得跟随任何字符
  3. between two ';' 在两个“;”之间 s any character could be there. s可能存在任何字符。
  4. Number of characters between two ";" 两个“;”之间的字符数 are 5. 是5。

I used following regex expression. 我使用了以下正则表达式。 But it doesn't give desired results. 但这并不能达到预期的效果。

(((.{0,5});){0,4}([^;]{0,5})){1}

Once the entire string is not matching it should be unmatched. 一旦整个字符串不匹配,就应该不匹配。

I'm not aware how to make the last character ';' 我不知道如何使最后一个字符“;” or empty. 或为空。 So that is not included in the logic above I've provided. 因此,以上所提供的逻辑中未包含该内容。

To elaborate more Following patterns are allowed. 为了详细说明,允许以下模式。

sdfsg;;;;;
sfdsf;sdfsd;sfsdf;;
;;;;

unmatching examples 无与伦比的例子

sdfsdf;sdfsd;sdf;sdfd;sdf;sdf;sdf

I'd really appreciate if somebody could help. 如果有人可以帮忙,我将不胜感激。 If you provide an solution please kindly give an explanation so it'll help to learn. 如果您提供解决方案,请给一个解释,以帮助学习。

Try this regex 试试这个正则表达式

^(?:[^;]{0,5};){1,4}(?:[^;]{0,5};?)?$

Visual explain https://regexper.com/#^%28%3F%3A[^%3B]{0%2C5}%3B%29{1%2C4}%28%3F%3A[^%3B]{0%2C5}%3B%3F%29%3F%24 视觉说明https://regexper.com/#^%28%3F%3A[^%3B]{0%2C5}%3B%29{1%2C4}%28%3F%3A[^%3B]{0 %2C5}%3B%3F%29%3F%24

  • With ^ we match start of Line ^匹配Line的开始
  • (?:) is a non capturing group (like () but don't store result to a groups) (?:)是一个非捕获组(例如()但不将结果存储到组中)
  • With [^;] we match all char except ; [^;]匹配除;以外的所有字符。
  • {0,5} catch 0 to 5 non ; {0,5}捕获0到5非; char 烧焦
  • ; at the end we have a final ; 最后我们有一个决赛;
  • {1,4} we match the previous pattern pattern from 1 to 4 time inclusive {1,4}我们将先前的模式从1到4次匹配
  • ;? the last ; 最后 ; is optinal but we can't have another char after 是可选的,但之后不能再有其他字符
  • $ the end of line $行尾

This regex matches all those rules 此正则表达式符合所有这些规则

^([^;]{0,5};){0,4}[^;]{0,5};?$

the ([^;]{0,5};) matches any set of letters or nothing before a semicolon and the semicolon itself, the {0,4} makes sure there aren't more than 4 semicolons before the last character, the [^;]{0,5} matches any character after the last semicolon, the ;? ([^;]{0,5};)与分号和分号本身之前的任何字母集或什么都不匹配, {0,4}确保最后一个字符(即[^;]{0,5}匹配最后一个分号;?之后的任何字符;? matches 1 or no semicolon as the very last character, and the $ makes sure there aren't any characters after the last semicolon. 匹配1或没有分号作为最后一个字符,并且$确保最后一个分号之后没有任何字符。

You can try this regex: 您可以尝试以下正则表达式:

(?:[^;]*;?){1,5}

It will capture anything between ; 它将捕获之间的任何东西; and upto 5 times. 最多5次

See demo at Regex101 请参阅Regex101上的演示

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

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