簡體   English   中英

非數字字符中包含的字符串的正則表達式單詞邊界

[英]regexp word boundary for strings enclosed in non alnum chars

我看過有關該主題的各種帖子,但找不到滿意的答案

我需要一個正則表達式來匹配像#xxx#這樣的字符串-這是一個字符串,可能在正面和背面具有不在az AZ 0-9中的字符-它在單詞邊界內-前后都帶有^或$或不在AZ AZ 0-9中的字符

我希望將其與不區分大小寫和全局匹配的替換一起使用,我正在尋找以下形式的解決方案:

#xxx#的正則表達式:

'#xxx#'.replace(regexp, 'bla') => 'bla'
'#xxx#,#xXx#)'.replace(regexp, 'bla') => 'bla,bla)'
'(#xXx#, #xxx#)'.replace(regexp, 'bla') => '(bla, bla)'

和:

'a#xxx#'.replace(regexp, 'bla') => 'a#xxx#'
'#xXx#0'.replace(regexp, 'bla') => '#xXx#0'
'hello'.replace(regexp, 'bla') => 'hello'

xxx的正則表達式:

'xxx'.replace(regexp, 'bla') => 'bla'
'xxx,xXx)'.replace(regexp, 'bla') => 'bla,bla)'
'(xXx, xxx),'.replace(regexp, 'bla') => '(bla, bla)'

和:

'axxx'.replace(regexp, 'bla') => 'axxx'
'xXx0'.replace(regexp, 'bla') => 'xXx0'
'hello'.replace(regexp, 'bla') => 'hello'

等等

我嘗試了各種解決方案(即(?!\\w)#xxx#(?!\\w) ),但無法使其正常工作。

基本上,我正在尋找\\ b在字符串中包含非數字字符時起作用。

有什么幫助嗎?

不知道我是否理解正確,而是將模式限制為

之前和之后是^或$或不在AZ AZ 0-9中的字符

您可以使用/(^|[^0-9a-zA-Z])pattern goes here([^0-9a-zA-Z]|$)/

  • (^|[^0-9a-zA-Z])將匹配字符串的開頭或不在0-9a-zA-Z中的字符;
  • 類似([^0-9a-zA-Z]|$)匹配字符串的結尾或不在0-9a-zA-Z中的char;

測試案例

1) #xxx#

 var samples = ['#xxx#', '#xxx#)', '(#xxx#,', 'a#xxx#', '#xxx#0', 'hello'] console.log( samples.map(s => s.replace(/(^|[^0-9a-zA-Z])#xxx#([^0-9a-zA-Z]|$)/, '$1bla$2')) ) 

2)對於xxx

 var samples = ['xxx', 'xxx)', '(xxx,', 'axxx', 'xxx0', 'hello'] console.log( samples.map(s => s.replace(/(^|[^0-9a-zA-Z])xxx([^0-9a-zA-Z]|$)/, '$1bla$2')) ) 

我不確定是否可以使用正則表達式解決方案,我使用了如下所示的javascript解決方案:

 const isAlnumChar = c => (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); const replace = (s, f, r) => { const lcs = s.toLowerCase(), lcf = f.toLowerCase(), flen = f.length; let res = '', pos = 0, next = lcs.indexOf(lcf, pos); if (next === -1) return s; do { if ((next === 0 || !isAlnumChar(s[next - 1])) && (next + flen === s.length || !isAlnumChar(s[next + flen]))) { res += s.substring(pos, next) + r; } else { res += s.substring(pos, next + flen); } pos = next + flen; } while ((next = lcs.indexOf(lcf, pos)) !== -1); return res + s.substring(pos); }; console.log(replace('#xxx#', '#xxx#', 'bla')); console.log(replace('#xxx#,#xXx#)', '#xxx#', 'bla')); console.log(replace('(#xXx#, #xxx#)', '#xxx#', 'bla')); console.log(replace('a#xxx#', '#xxx#', 'bla')); console.log(replace('#xXx#0', '#xxx#', 'bla')); console.log(replace('hello', '#xxx#', 'bla')); console.log(replace('xxx', 'xxx', 'bla')); console.log(replace('xxx,xXx)', 'xxx', 'bla')); console.log(replace('(xXx, xxx),', 'xxx', 'bla')); console.log(replace('axxx', 'xxx', 'bla')); console.log(replace('xXx0', 'xxx', 'bla')); console.log(replace('hello', 'xxx', 'bla')); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM