简体   繁体   English

在JavaScript中使用正则表达式验证缩写

[英]Validating initials with regex in JavaScript

I want to validate my initials with regex in JavaScript, the rule should match any letter combination and should not be case sensitive. 我想用JavaScript中的正则表达式来验证我的姓名首字母,该规则应匹配任何字母组合,并且不区分大小写。

Example (Liza Suki): 范例(Liza Suki):

var a = "ls"; // valid
var b = "sl"; // valid
var c = "Ls"; // valid
var d = "LS"; // valid
var e = "lS"; // valid
var f = "Sl"; // valid
var g = "SL"; // valid
var h = "sL"; // valid

Thanks in advance. 提前致谢。

Try this one (the 'i' flag means, that regex is case-insensitive): 试试这个(“ i”标志表示,正则表达式不区分大小写):

/(ls)|(sl)/i

https://regex101.com/r/mT8jW3/2 https://regex101.com/r/mT8jW3/2

Anchors must be a needed one. 锚一定是必需的。

/^[ls]{2}$/i

Try this if you don't want to match ll or ss 如果您不想匹配llss请尝试此操作

/^(?!(?:ss|ll)$)[ls]{2}$/i

DEMO 演示

i不区分大小写, g是全局的:

/(ls)|(sl)/ig
var regex = /(ls)|(sl)/i;
console.log(regex.test('LS'));
console.log(regex.test('lS'));
console.log(regex.test('Ls'));
console.log(regex.test('sL'));
console.log(regex.test('ll'));
console.log(regex.test('SS'));

Output 输出量

true
true
true
true
false
false

Here is a generic function that takes a name and input initials value and it validates whether name has same initials or not. 这是一个通用函数,它接受名称并输入缩写名称,并验证名称是否具有相同的缩写。

function isValid(name, ils) {
    var m = name.match(/\b[A-Z]/g);
    var re = new RegExp('^' + m.map(function(e){return '(?=.*?' + e + ')';}).join('') +
              '[' + m.join('') + ']{' + m.length + '}$', 'i');

    // Example: re = /^(?=.*?s)(?=.*?l)[sl]{2}$/i
    return re.test(ils);
}

Testing: 测试:

isValid('Liza Suki', 'sl')
true
isValid('Liza Suki', 'ss')
false
isValid('Liza Suki', 'ls')
true
isValid('Liza Suki', 'LS')
true
isValid('Liza Suki', 'LL')
false
isValid('Liza Suki', 'lsl')
false

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

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