我需要匹配文本以在客户端进行搜索。 我有:
const regex = /zitiste/g;
我需要匹配它:
const place = "žitište";
place.match(regex);
这还会在以下情况下返回false:
https://regex101.com/r/Tk7tKy/2
“ zitiste”与“žitište”不匹配
因此甚至有可能将z与ž匹配?使用正则表达式。 我读了100页带有正则表达式的页面,但即使有可能也无法捕捉。
答案 0 :(得分:1)
您可以匹配z
或 ž
(与s
/ š
相同)
const regex = /[zž]iti[sš]te/gi;
实时示例:
const regex = /[zž]iti[sš]te/gi;
console.log("žitište".match(regex));
console.log("žitiste".match(regex));
console.log("Zitište".match(regex));
console.log("Zitiste".match(regex));
.as-console-wrapper {
max-height: 100% !important;
}
[zž]
的意思是“ z
或ž
。”
很明显,您要为要允许带有或不带有变音符号的任何其他字母提供其他替代方法。
我希望您可能能够使用新的Unicode属性转义功能来搜索塞尔维亚语脚本中的所有内容,但doesn't look like it gets its own category是可以的。 :-(
在此示例中,您从输入中获取正则表达式,然后松开它以允许带有或不带有变音符的字符(在这种情况下,仅z
和s
出现在您的问题中,但是您将要添加完整列表):
// The substitutions to make
const map = {
"z": "[zž]",
"ž": "[zž]",
"s": "[sš]",
"š": "[sš]",
};
document.getElementById("btn-check").addEventListener("click", function() {
let rexText = document.getElementById("regex").value;
rexText = rexText.replace(/[zžsš\\]/g, ch => map[ch] || ch);
const rex = new RegExp(rexText, "gi");
const text = document.getElementById("input").value;
const result = text.match(rex);
console.log(`Matching text "${text}" against ${rex}: ${result}`);
});
<div>
<label>
Regex:
<input type="text" id="regex" value="zitiste">
</label>
</div>
<div>
<label>
Input to match against:
<input type="text" id="input" value="žitište">
</label>
</div>
<input type="button" value="Check" id="btn-check">