![](/img/trans.png)
[英]Regular expression for matching single occurrence of ' (single quote) coming only between alphabets not on start or end of the string
[英]Regular expression to remove anything but alphabets and '[single quote]
如何更改此正則表達式以從字符串中刪除除字母和 '(單引號)之外的所有內容?
pattern = /\b(ma?c)?([a-z]+)/ig;
要刪除字符,您需要使用實際執行此操作的功能,例如字符串replace
函數(它可以接受正則表達式作為“from”參數)。
然后,您只是在處理字符類的正常應用程序,它在 JavaScript(以及大多數其他正則表達式變體)中使用[...]
描述,其中...
是類中應該包含的內容。 您可以在開頭使用^
來反轉類的含義:
在你的情況下,它可能是:
str = str.replace(/[^A-Za-z']/g, "");
...它將替換除英文字符 AZ (ABCDEFGHIJKLMNOPQRSTUVWXYZ)、az (abcdefghijklmnopqrstuvwxyz) 和單引號之外的任何內容(例如,將其刪除)。
let str = "This is a test with the numbers 123 and a '."; console.log("before:", str); str = str.replace(/[^A-Za-z']/g, ""); console.log("after: ", str);
但是,請注意,英語中不使用的字母字符也不例外,網絡上使用的各種語言中都有很多字母字符(甚至,在英語中,在“借用”詞中,例如“voilà”和“幼稚的”)。
你已經說過你只用英語 AZ 就可以了,但對於其他人來說:在支持 ES2018 及更高版本的Unicode 屬性匹配的環境中,你可以處理任何被 Unicode 視為“字母”的東西,而不僅僅是 AZ 使用\\p{Alpha}
屬性。 \\p
表示“匹配這個 Unicode 屬性”(像往常一樣,小寫版本\\p
表示“匹配”,大寫版本\\P
表示“不匹配”), {Alpha}
表示“字母”:
str = str.replace(/[^\p{Alpha}']/gu, "");
(請注意, \\p{Alpha}
再次表示“字母”,但由於它屬於否定字符類,因此我們排除了字母字符。)
請注意上面的u
標志,以啟用更新的 Unicode 功能。 這也處理了“voilà”和“naïve”的例子:
let str = "This is a test with the numbers 123 and a ' and voilà and naïve."; console.log("before:", str); str = str.replace(/[^\\p{Alpha}']/gu, ""); console.log("after: ", str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.