正则表达式:在字符串的开头/结尾匹配所需的字符

4 javascript regex

我需要一个正则表达式来完全匹配'AB'在字符串开头或结尾设置的字符,并用替换它们''。注意:仅当它全部出现时,它才不应该与该字符集的部分匹配。

  1. 因此,如果有'AB Some AB company name AB',它应该返回'Some AB company name'
  2. 如果有的话'Balder Storstad AB',它应该只删除'AB'而不是'B'开始时删除,因为它不是整体'AB',而是一部分。

我试过的是:

name.replace(/^[\\AB]+|[\\AB]+$/g, "");
Run Code Online (Sandbox Code Playgroud)

直到在字符串的开头或结尾遇到单个“ A”或“ B”为止都是可以的。如果测试字符串是开头和结尾'Balder Storstad AB'都匹配并返回。它应该在开头或结尾处跳过单个或单个。'B''AB''alder Storstad''B''A'

我的正则表达式有什么问题?

编辑:

我忘记添加了。如果测试字符串为:“ ABrakadabra AB”或“ Some text haha​​hAB”或“ ABAB text text textABAB”

不应匹配“ AB”,因为它们不是单独的“ AB”组,而是其他词的一部分。

MrG*_*eek 5

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, "")
);
Run Code Online (Sandbox Code Playgroud)
说明:

(^AB\s+) // AB at the beginning (^) with some spaces after it
| // Or
(\s+AB$) // AB at the end ($) with some spaces before it
Run Code Online (Sandbox Code Playgroud)