我正在尝试获取名称字符串的缩写,但是字符串可能包含一个我想忽略的标题,并且具有多个或单个名称。仅使用Java中的Regex怎么做?
我可以用\b(\w)
匹配字符串中单词的第一个字符,但是我想忽略“Mr”和“Mrs”等。
有点像.. [^mr]\b(\w)
,但这会在前面加上mr和空格中的M,并且不会忽略其他任何标题
示例字符串和匹配项:
'Mr Bob Smith' -> BS
'Miss Jessica Blue' -> JB
'tim white' -> TW
'dr Lisa S pink' -> LS
'lord Lee Kensington-Smithe' -> LK
最佳答案
我可以使用负面的前瞻和正面的关注来解决此问题。
您可以尝试以下方法:
function firstChars(str) {
const regex = /(?!\bmr\.?\b|\bmiss\b|\blord\b|\bdr\b)((?<=\s)|(?<=^))(\b[a-z])/ig;
const matches = [...str.match(regex)];
return matches.map(char => char.toUpperCase()).join('');
}
console.log(firstChars('Mr Bob Smith'));
console.log(firstChars('Miss Jessica Blue'));
console.log(firstChars('tim white'));
console.log(firstChars('dr Lisa S pink'));
console.log(firstChars('Drone Picker'));
console.log(firstChars('lord Lee Kensington-Smithe'));
.as-console-wrapper{min-height: 100%!important; top: 0}
关于javascript - 使用正则表达式匹配名称字符串中的首字母,忽略标题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61525030/