gpt4 book ai didi

javascript - 匹配以首字母开头后跟有效字母字符串的字符串 - 正则表达式

转载 作者:行者123 更新时间:2023-11-29 19:01:49 25 4
gpt4 key购买 nike

我试图匹配以 (Mr.|Mrs.|Ms.|Dr.|Er.) 开头的字符串,后跟任何字符串 [a-zA-Z] 但不知何故,它也将其传递为“Er” .博士”。

让我知道我在这里的正则表达式做错了什么。

var input = [
{str: "Mr.X", expectedValue: true},
{str: "Mrs.Y", expectedValue: true},
{str: "Dr#Joseph", expectedValue: false},
{str: "Er .Abc", expectedValue: false},
{str: "Er.Dr.", expectedValue: false},
{str: "Er.Abc", expectedValue: true}
];

var re = /^(Mr|Mrs|Ms|Dr|Er)\.+[A-Za-z]/;

input.forEach(x => {
var answer;
var matchStr;
answer = re.test(x.str);
matchStr = x.expectedValue === answer ? "MATCH" : "NO MATCH";
console.log("------------------------------------------------------------------------------");
console.log(`"${x.str}" | Expected Output: ${x.expectedValue} | My Output: ${answer} | ${matchStr}`);
console.log("------------------------------------------------------------------------------");
})

输出 -

Regex 2

最佳答案

您可以稍微更改一下正则表达式,从

/^(Mr|Mrs|Ms|Dr|Er)\.+[A-Za-z]/

/^(Mr|Mrs|Ms|Dr|Er)\.[A-Za-z]+$/

没有多个 . 并检查字母直到字符串末尾。

var input = [
{str: "Mr.X", expectedValue: true},
{str: "Mrs.Y", expectedValue: true},
{str: "Dr#Joseph", expectedValue: false},
{str: "Er .Abc", expectedValue: false},
{str: "Er.Dr.", expectedValue: false},
{str: "Er.Abc", expectedValue: true}
];

var re = /^(Mr|Mrs|Ms|Dr|Er)\.[A-Za-z]+$/;

input.forEach(x => {
var answer;
var matchStr;
answer = re.test(x.str);
matchStr = x.expectedValue === answer ? "MATCH" : "NO MATCH";
console.log(`"${x.str}" | Expected Output: ${x.expectedValue} | My Output: ${answer} | ${matchStr}`);
})

关于javascript - 匹配以首字母开头后跟有效字母字符串的字符串 - 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46388733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com