我没有看到regexp,但我知道数字是[0-9]
,大写字母是[A-Z]
。
我想知道的是:如何过滤掉与正则表达式匹配的字符串中的某些单词,并对其进行样式设置。例如:
string s = 'Hello ABC1 world C2DF !';
//magic code here
//result:
'Hello <b>ABC1</b> world <b>C2DF</b> !'
答案 0 :(得分:3)
这个应该符合您的需求:
/[0-9][A-Z]{3}|[A-Z][0-9][A-Z]{2}|[A-Z]{2}[0-9][A-Z]|[A-Z]{3}[0-9]/
匹配(仅匹配):
0ABC
A0BC
AB0C
ABC0
当然,在上面的列表中,A
,B
和C
可以是任何大写字母,而0
可以是任意数字。
答案 1 :(得分:2)
使用此正则表达式:
/\b(\d[A-Z]{3}|[A-Z]\d[A-Z]{2}|[A-Z]{2}\d[A-Z]|[A-Z]{3}\d)\b/
使用replace method in javascript:
s.replace(/\b(\d[A-Z]{3}|[A-Z]\d[A-Z]{2}|[A-Z]{2}\d[A-Z]|[A-Z]{3}\d)\b/g,"<b>$&</b>");
经测试的脚本:
var output,
text = "9GHJ is saying hello to ABC1 world C2DF, but 89UI is showing up with his friend HUIP, nothing to do, they are not welcome ! As garyh said, these NUMB3RZ should not be replaced",
regex = /\b(\d[A-Z]{3}|[A-Z]\d[A-Z]{2}|[A-Z]{2}\d[A-Z]|[A-Z]{3}\d)\b/g,
replace = "<b>$&</b>";
output = text.replace(regex,replace)
console.log ( output );
将输出:
<b>9GHJ</b> is saying hello to <b>ABC1</b> world <b>C2DF</b>, but 89UI is showing up with his friend HUIP, nothing to do, they are not welcome ! As garyh said, these NUMB3RZ should not be replaced
答案 2 :(得分:2)
要解决此问题,您肯定需要word boundaries。另一种解决方案也将匹配,例如在“1ABCD”上,突出显示前四个字符。
我的解决方案涉及look ahead,但如果您不希望这样,只需将边界\b
带到您自己的解决方案中。
\b(?=[^\d]*\d[^\d]*)[A-Z\d]{4}\b
我将4个字符的单词与[A-Z\d]{4}
单词边界\b
相匹配,确保之前或之前没有其他字母或数字。积极的前瞻(?=[^\d]*\d[^\d]*)
确保满足您对一位数的要求。