[英]Regex: Match desired chars at the beginning/end of string
我需要一個正則表達式來完全匹配在字符串開頭或結尾設置的'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'
並返回'alder Storstad'
。 它應該在開頭或結尾跳過單個'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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.