簡體   English   中英

正則表達式從字符串中刪除前導和尾隨特殊字符和空格

[英]Regex to remove leading and trailing special characters and spaces from string

我試圖找到一個正則表達式來刪除所有前導/尾隨空格以及所有前導/尾隨特殊字符。

如果我有字符串:

test = '~!#@$@  hello this is a #! test  ^^#!^^    '

我希望它返回為:

'hello this is a #! test'

因此保留了第一個和最后一個字母之間的特殊字符和空格,但所有前導/尾隨字符都被刪除。 現在我有這個:

test.replace(/[^a-zA-Z ]/g,"").replace(/^\s+|\s+$/g, "")

返回:

'hello this is a  test'

所以它正在刪除所有特殊字符和前導/尾隨空格。 我怎樣才能保留那個“#?” 在“a”和“test”之間?

通過使用 unicode 標志u ,您可以在負字符 class [^...]中使用字母\p{L}和數字\p{N}的 Unicode類別
並在開頭匹配它們^| 在最后$得到任何不是字母或數字的尾隨或前導的東西。

圖案:

^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$

測試片段:

 let test = '~;#@$@ hello this is a #. test ^^#,^^ '; test = test.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu; ''); document.write('['+test+']');

暫無
暫無

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

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