简体   繁体   English

javascript 正则表达式用于特殊条件

[英]javascript regex for special condition

I am trying to create regex for below condition:我正在尝试为以下条件创建正则表达式:

Allowed characters: letters (az) (not case sensitive), min-length: 1, max-length: 255.允许的字符:字母 (az)(不区分大小写),最小长度:1,最大长度:255。

Numbers and Special Characters (except @,$,%,^) are only allowed in combination with words (az texts).数字和特殊字符(@、$、%、^ 除外)只能与单词(az 文本)组合使用。

Consecutive special characters are not allowed.不允许使用连续的特殊字符。

Numbers (up to 4 together) and/or 1 special character can appear in combination with words.数字(最多 4 个)和/或 1 个特殊字符可以与单词组合出现。

Ex:前任:

9900Acres 9900英亩

Grey Hound!灰猎犬!

[Roy]Media [罗伊]媒体

Cool,boy酷男孩

are all allowed.都是允许的。

I can't seem to get the hang of it.我似乎无法掌握它。

I tried creating this regex -我尝试创建这个正则表达式 -

^(?:((([0-9]{0,4})[ ]{0,})([!#&*()<,>.?/{}\[\]_-]{0,1})([0-9]{0,4})[a-zA-Z]{1,255}(([0-9]{0,4})([ ]{0,})([0-9]{0,4}))([!#&*()<,>.?/{}\[\]_-]{0,1}))+){3,}$

but with no success但没有成功

challenge accepted:已接受的挑战:

instead of one mega-regex, break it down:而不是一个大型正则表达式,将其分解:

function isValid(text = '') {
  if (!text.length || text.length > 255) {
    return false;
  }

  // check if there are more than 4 consecutive numbers
  if (/[0-9]{5,}/.test(text)) {
    return false;
  }

  // check if there are 2 consecutive special characters
  if (/[!#&*()<,>.?/{}[\]_-]{2,}/.test(text)) {
    return false;
  }

  return true; // should be fine ?
}

console.log(isValid('9900Acres')); // true
console.log(isValid('Grey Hound!')); // true
console.log(isValid('[Roy]Media')); // true
console.log(isValid('Cool,boy')); // true

Try with this:试试这个:

^(?=.*[A-Za-z])(?!.*[^a-zA-Z\d\n]{2})(?!(?:.*[^\da-zA-Z\n])?\d+(?:[^\da-zA-Z\n].*)?$)[ !#&*()<,>.?\/{}\[\]\w-]{1,255}$

Explained:解释:

^ # Start of line / String
    
    # Lookahead: whatever + some letter
    (?=.*[A-Za-z])
    
    # negative lookahead: whatever + 2 consecutive forbidden characters
    (?!.*[^a-zA-Z\d\n]{2})
    
    # negative lookahead to forbid numbers without letters on some of the sides:
    (?!
        (?:.*[^\da-zA-Z\n])?  # Optional: something + special character
        \d+                   # numbers
        (?:[^\da-zA-Z\n].*)?$ # Optional: special character + something + end of string
    )

    # All allowed characters 1 to 255 times
    [ !#&*()<,>.?\/{}\[\]\w-]{1,255}
$ # End of line / string

You have a demo here在这里有一个演示

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

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