我对正则表达式的研究不多,但我知道数字是[0-9]
,大写字母是[A-Z]
。
我想知道的是:如何从匹配正则表达式的字符串中过滤掉某些单词,并设置它们的样式。例如:
string s = 'Hello ABC1 world C2DF !';
//magic code here
//result:
'Hello <b>ABC1</b> world <b>C2DF</b> !'
我对正则表达式的研究不多,但我知道数字是[0-9]
,大写字母是[A-Z]
。
我想知道的是:如何从匹配正则表达式的字符串中过滤掉某些单词,并设置它们的样式。例如:
string s = 'Hello ABC1 world C2DF !';
//magic code here
//result:
'Hello <b>ABC1</b> world <b>C2DF</b> !'
这应该符合您的需求:
/[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
可以是任何数字。
使用这个正则表达式:
/\b(\d[A-Z]{3}|[A-Z]\d[A-Z]{2}|[A-Z]{2}\d[A-Z]|[A-Z]{3}\d)\b/
在 javascript 中使用replace 方法:
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