简体   繁体   English

重复模式的正则表达式

[英]Regex for repeating pattern

I need a regex which satisfies the following conditions. 我需要一个满足以下条件的正则表达式。 1. Total length of string 300 characters. 1.字符串总长度300个字符。 2. Should start with &,-,/,# only followed by 3 or 4 alphanumeric characters 3. This above pattern can be in continuous string upto 300 characters 2.应以&,-,/,#开头,后面只跟3 or 4 alphanumeric characters 3.上面的图案可以连续字符串,最多300 characters

String example - &ACK2-ASD3#RERT... 字符串示例 - &ACK2-ASD3#RERT ...

I have tried repeating the group but unsuccessful. 我试过重复这个小组但不成功。

(^[&//-#][A-Za-z0-9]{3,4})+ 

That is not working ..just matches the first set 这不起作用..只是匹配第一组

You may validate the string first using /^(?:[&\\/#-][A-Za-z0-9]{3,4})+$/ regex and checking the string length (using s.length <= 300 ) and then return all matches with a part of the validation regex: 您可以首先使用/^(?:[&\\/#-][A-Za-z0-9]{3,4})+$/ regex验证字符串并检查字符串长度(使用s.length <= 300 )然后返回所有匹配与验证正则表达式的一部分:

 var s = "&ACK2-ASD3#RERT"; var val_rx = /^(?:[&\\/#-][A-Za-z0-9]{3,4})+$/; if (val_rx.test(s) && s.length <= 300) { console.log(s.match(/[&\\/#-][A-Za-z0-9]{3,4}/g)); } 

Regex details 正则表达式细节

  • ^ - start of string ^ - 字符串的开头
  • (?:[&\\/#-][A-Za-z0-9]{3,4})+ - 1 or more occurrences of: (?:[&\\/#-][A-Za-z0-9]{3,4})+ - 出现1次或多次:
    • [&\\/#-] - & , / , # or - [&\\/#-] - &/#-
    • [A-Za-z0-9]{3,4} - three or four alphanumeric chars [A-Za-z0-9]{3,4} - 三个或四个字母数字字符
  • $ - end of string. $ - 结束字符串。

See the regex demo . 请参阅正则表达式演示

Note the absence of g modifier with the validation regex used with RegExp#test and it must be present in the extraction regex (as we need to check the string only once, but extract multiple occurrences). 请注意,缺少g修饰符,并且验证正则表达式与RegExp#test一起使用,并且它必须存在于提取正则表达式中(因为我们只需检查字符串一次,但提取多次出现)。

You're close. 你很亲密 Add the lookahead: (?=.{0,300}$) to the start to make it satisfy the length requirement and do it with pure RegExp: 将前瞻: (?=.{0,300}$)到开头以使其满足长度要求并使用纯RegExp执行:

/(?=.{0,300}$)^([&\-#][A-Za-z0-9]{3,4})+$/.test("&ACK2-ASD3#RERT")

You can try the following regex . 您可以尝试以下正则表达式

 const regex = /^([&\\/\\-#][A-Za-z0-9]{3,4}){0,300}$/g; const str = `&ACK2-ASD3#RERT`; if (regex.test(str)) { console.log("Match"); } 

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

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