如何解决此正则表达式,以免碰到HYDRAULIC
之类的扩展,而仅将HYD
和HYD.
转换为HYDRAULIC
并解决空间问题(对于HYD.CYLINDER
)?
Link of regex
正则表达式(hyd.
和hyd
):
\b(hyd)(?:\s|$|[^\w])
测试字符串:
HYD. CYLINDER
HYD CYLINDER
HYD.CYLINDER
HYDRAULIC CYLINDER
CYLINDER,HYD.
CYLINDER,HYDRAULIC
CYLINDER,HYD
CYLINDER, HYD.
CYLINDER, HYDRAULIC
CYLINDER,HYD
替代:
HYDRAULIC
HYDRAULIC CYLINDER
HYDRAULICCYLINDER
HYDRAULICCYLINDER
HYDRAULIC CYLINDER
CYLINDER,HYDRAULIC
CYLINDER,HYDRAULIC
CYLINDER,HYDRAULICCYLINDER, HYDRAULIC
CYLINDER, HYDRAULIC
CYLINDER,HYDRAULIC
最佳答案
您可以使用
s = s.replace(/\bhyd(?:\.|\b)([a-z0-9]?)/gi, function($0, $1) {
return "HYDRAULIC" + ($1 ? " " + $1 : "") ;
})
请参见regex demo。
正则表达式详细信息
\b
-前导词边界hyd
-子字符串(?:\.|\b)
-点或字边界([a-z0-9]?)
-捕获组1:一个可选的字母数字字符。如果组1匹配,则将匹配项替换为
HYDRAULIC
+空格+在组1中捕获的字母,否则,将其替换为HYDRAULIC
。请注意,
\bhyd(?:\.|\b)
和\bhyd\b\.?
suggested by The fourth bird是同义词。JS演示:
var strs = ['HYD. CYLINDER','HYD CYLINDER','HYD.CYLINDER','HYDRAULIC CYLINDER','CYLINDER,HYD.','CYLINDER,HYDRAULIC','CYLINDER,HYD','CYLINDER, HYD.','CYLINDER, HYDRAULIC','CYLINDER,HYD'];
var rx = /\bhyd(?:\.|\b)([a-z0-9]?)/gi;
for (var s of strs) {
console.log(s, "=>", s.replace(rx, function($0, $1) {
return "HYDRAULIC" + ($1 ? " " + $1 : "") ;
}))
}