简体   繁体   English

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

[英]Regex: Match desired chars at the beginning/end of string

I need a regex to match exactly 'AB' chars set at the beginning or at the end of the string and replace them with '' .我需要一个正则表达式来完全匹配在字符串开头或结尾设置的'AB'字符,并将它们替换为'' Note: it should not match parts of that chars set, only if it occurs whole.注意:它不应该匹配该字符集的部分,只有当它出现时才完整。

  1. So if I have 'AB Some AB company name AB' , it should return 'Some AB company name' .所以如果我有'AB Some AB company name AB' ,它应该返回'Some AB company name'
  2. If I have 'Balder Storstad AB' , it should remove only 'AB' and not the 'B' at the beginning because it is not whole 'AB' , only the part of it.如果我有'Balder Storstad AB' ,它应该只删除'AB'而不是开头的'B'因为它不是整个'AB' ,只是它的一部分。

What I tried is:我尝试的是:

name.replace(/^[\\AB]+|[\\AB]+$/g, "");

And it is OK until single "A" or "B" encountered at the beginning or end of the string.直到在字符串的开头或结尾遇到单个“A”或“B”都可以。 If test string is 'Balder Storstad AB' it matches both 'B' at the beginning and 'AB' at the end and returns 'alder Storstad' .如果测试字符串是'Balder Storstad AB'它匹配开头'B'和结尾'AB'并返回'alder Storstad' It should skip single 'B' or single 'A' at the beginning or end.它应该在开头或结尾跳过单个'B'或单个'A'

What is wrong in my regex?我的正则表达式有什么问题?

EDIT:编辑:

I forgot to add this.我忘了添加这个。 If test strings are: "ABrakadabra AB" or "Some text hahahAB" or "ABAB text text textABAB"如果测试字符串是:“ABrakadabra AB”或“Some text haha​​hAB”或“ABAB text text textABAB”

"AB" should not be matched because they are not separate "AB" groups but part of other word.不应匹配“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, ""));

Explanation :解释 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM