我需要一个正则表达式来精确匹配设置在字符串开头或结尾的 'AB'
字符,并将它们替换为 ''
。注意:它不应该匹配该字符集的部分,只有当它出现时才完整。
- 所以如果我有
'AB Some AB company name AB'
,它应该返回'Some AB company name'
。 - 如果我有
'Balder Storstad AB'
,它应该只删除'AB'
而不是开头的'B'
因为它不是完整的'AB'
,只是它的一部分。
我试过的是:
name.replace(/^[\\AB]+|[\\AB]+$/g, "");
直到在字符串的开头或结尾遇到单个“A”或“B”才可以。如果测试字符串是 'Balder Storstad AB'
它匹配开头的 'B'
和结尾的 'AB'
并返回 '桤木斯托斯塔德'
。它应该在开头或结尾跳过单个 'B'
或单个 'A'
。
我的正则表达式有什么问题?
编辑:
我忘记添加这个了。如果测试字符串是: “ABrakadabra AB”或“Some text hahahAB”或“ABAB text text textABAB”
不应匹配“AB”,因为它们不是单独的“AB”组,而是其他词的一部分。
最佳答案
var rgx = /(^AB\s+)|(\s+AB$)/g;
console.log("AB Some AB company name AB".replace(rgx, ""));
console.log("Balder Storstad AB".replace(rgx, ""));
console.log("ABrakadabra AB".replace(rgx, ""));
console.log("Some text hahahAB".replace(rgx, ""));
console.log("ABAB text text textABAB".replace(rgx, ""));
解释:
(^AB\s+) // AB at the beginning (^) with some spaces after it
| // Or
(\s+AB$) // AB at the end ($) with some spaces before it
关于javascript - 正则表达式:在字符串的开头/结尾匹配所需的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46055789/