我这里有一个脚本,通过点击按钮来改变文本区域的值。我使用Javascript与RegEx一起替换。所以每个数字都有一个指定的值
然而,在这个示例中,我不能在破折号后面加上字母。工作。
const mapper = new Map();
mapper.set("10th", "11th");
mapper.set("-", "Deleted");
mapper.set("63-51", "40");
mapper.set("121AA", "95");
mapper.set("121-I", "Deleted");
mapper.set("121-OO", "Deleted");
function fixtext() {
const elm = document.getElementById("textarea1");
if (elm) {
elm.value = elm.value
.replace(
/bd+(?:[A-Z]|([A-Z])1|d|th|st|nd)?(|-d+)?b/g,
m => mapper.has(m) ? mapper.get(m) : m
);
}
}
<textarea id="textarea1" rows="4" cols="50">121AA will become 95 and 63-51 will become 40. This should be the same for 121-I and 121-OO.</textarea>
<button class="nbtngreen" onclick="fixtext()">Update</button>
因此,点击按钮后,121-I
应变为指定的Deleted
。121-OO
也是如此。
我很感激如何修复我正在使用的RegEx的任何帮助。提前感谢!
您的regexp只匹配-
之后的d+
。将其更改为[A-Zd]+
以匹配那里的字母或数字。
您不需要在具有?
量词的组中使用空字符串作为替代,因为量词意味着其他模式是可选的。
[A-Z]|([A-Z])1
可以简化为([A-Z])1?
。
const mapper = new Map();
mapper.set("10th", "11th");
mapper.set("-", "Deleted");
mapper.set("63-51", "40");
mapper.set("121AA", "95");
mapper.set("121-I", "Deleted");
mapper.set("121-OO", "Deleted");
function fixtext() {
const elm = document.getElementById("textarea1");
if (elm) {
elm.value = elm.value
.replace(
/bd+(?:([A-Z])1?|d|th|st|nd)?(-[A-Zd]+)?b/g,
m => mapper.has(m) ? mapper.get(m) : m
);
}
}
<textarea id="textarea1" rows="4" cols="50">121AA will become 95 and 63-51 will become 40. This should be the same for 121-I and 121-OO.</textarea>
<button class="nbtngreen" onclick="fixtext()">Update</button>