JavaScript正则表达式以匹配单词边界和发音符号
我必须在文本文档中匹配单词边界,以匹配带有变音符号的单词。给定一个JavaScript正则表达式以匹配单词边界和发音符号,javascript,regex,Javascript,Regex,我必须在文本文档中匹配单词边界,以匹配带有变音符号的单词。给定一个word标记,我的正则表达式看起来像 var wordRegex = new RegExp("\\b(" + word + ")\\b", "g"); while ((match = wordRegex.exec(text)) !== null) { if (match.index > (seen.get(token) || -1)) {
word
标记,我的正则表达式看起来像
var wordRegex = new RegExp("\\b(" + word + ")\\b", "g");
while ((match = wordRegex.exec(text)) !== null) {
if (match.index > (seen.get(token) || -1)) {
var wordStart = match.index;
var wordEnd = wordStart + token.length - 1;
item.characterOffsetBegin = wordStart;
item.characterOffsetEnd = wordEnd;
seen.set(token, wordEnd);
break;
}
}
这适用于普通单词,如ciao
,casa
,但当我在文本中有però
,così
等单词时,它将不起作用
const seen=new Map();
var text=“Ci son macchine nascoste e,però,nascoste male”
变量标记=文本分割(/[a-zA-Z0-9è
tokens.forEach((token,tokenIndex)=>{
变量项={
“索引”:(令牌索引+1),
“字”:代币
}
var-escaped=token.replace(/[\-\[\]{}()*+?,\\\^$\\\\s]/g,“\\$&”);
var wordRegex=newregexp(“\\b(“+escaped+”)\\b”,“g”);
var match=null;
console.log(令牌“--->”,wordRegex)
while((match=wordRegex.exec(text))!==null){
console.log(“\t-->”,match.index)
if(match.index>(seen.get(token)| |-1)){
var wordStart=match.index;
var wordEnd=wordStart+token.length-1;
item.characterOffsetBegin=wordStart;
item.characterOffsetEnd=wordEnd;
seen.set(令牌,wordEnd);
打破
}
}
})
这是我们在注释中提出的解决方案,用于将具有变音符号的单词映射到文本中的索引:
function removeDiacritics(文本){
返回去毛刺(文本)
}
const seen=新映射();
var text=“Ci son macchine nascoste e,però,nascoste male”
变量标记=文本分割(/[a-zA-Z0-9è
var normalizedText=远程视频点评(文本)
tokens.forEach((token,tokenIndex)=>{
变量项={
“索引”:(令牌索引+1),
“单词”:移除的语音符号(标记)
}
var-escaped=token.replace(/[\-\[\]{}()*+?,\\\^$\\\\s]/g,“\\$&”);
转义=removeDiacritics(转义)
var wordRegex=newregexp(“\\b(“+escaped+”)\\b”,“g”);
var match=null;
console.log(令牌“--->”,wordRegex)
while((match=wordRegex.exec(normalizedText))!==null){
console.log(“\t-->”,match.index)
if(match.index>(seen.get(token)| |-1)){
var wordStart=match.index;
var wordEnd=wordStart+token.length-1;
item.characterOffsetBegin=wordStart;
item.characterOffsetEnd=wordEnd;
seen.set(令牌,wordEnd);
打破
}
}
})
这可能对您的具体情况没有帮助,但在执行regex:.@AndrewA.谢谢,这是一个问题:问题是在去毛刺后,为了与文本中的原始字符串匹配,可能需要去除“word”输入的毛刺。“让我试试。”安德烈瓦。所以问题当然是deburr('però')
将变成pero
。之后正则表达式将不匹配。这里是lodash之外的去毛刺函数:我认为如果你也去毛刺正则表达式本身,它可以工作,你仍然可以在这个例子中看到带变音符号的原始单词:。这就是你要找的吗?@AndrewA。它可以工作!谢谢,请张贴你的答案。如果有任何关于正则表达式的答案,你的答案就是!