簡體   English   中英

正則表達式-除字符串外的所有內容

[英]Regex - everything except string

我想用給定的char替換每個不是字符串的char,例如| ; 管他呢。 我有簡單的正則表達式模式: ([a-zA-Z])\\w+

...問題是要替換該模式匹配項以外的所有內容。

例如: qwerty 123456 ;,.'[]?/ asd

結果: qwerty|||||||||||||||||asd

提前致謝。

您可以通過兩種方式過濾/匹配/替換

第一變體:

[a-z0-9] // filter/match/replace everything that is included in the defined Character set

第二變體:

[^a-z0-9] // filter/match/replace everything that is NOT included in the defined Character set

如您所見,唯一的區別是^ ^是字符集中的否定運算符。

  • 您可以使用^否定字符集中的字符。
  • \\w需要省略,因為否則它還將嘗試匹配任何單詞字符
  • 不需要括號,因為不需要分組單個字符集,並且您沒有使用對該捕獲組的backreference

這將導致以下正則表達式:

[^a-zA-Z]+

對於此輸入:
qwerty 123456 ;,.'[]?/ asd
您要匹配所有非單詞數字 ,因此可以使用[\\W\\d]

但是,由於您想一次一次地替換它們,而不是一次全部替換,因此您無需使用量詞+

您也可以使用:內置字符類(如果您的引擎語言包含它們)。 例如:

[:alnum:]       all letters and digits
[:alpha:]       all letters
[:blank:]       all horizontal whitespace
[:cntrl:]       all control characters
[:digit:]       all digits
[:graph:]       all printable characters, not including space
[:lower:]       all lower case letters
[:print:]       all printable characters, including space
[:punct:]       all punctuation characters
[:space:]       all horizontal or vertical whitespace
[:upper:]       all upper case letters
[:xdigit:]      all hexadecimal digits

觀看Perl的巨星測試

echo "qwerty 123456 ;,.'[]?/ asd" | perl -lpe 's/[[:cntrl:][:punct:]\d ]/|/g'  

要么:

echo "qwerty 123456 ;,.'[]?/ asd" | perl -lpe 's/[\W\d]/|/g'  

具有相同的輸出:

qwerty|||||||||||||||||asd

注意:

有關更多詳細信息,請參見: 正則表達式參考:速記字符類

暫無
暫無

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

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