簡體   English   中英

從字符串中的單詞的開頭和結尾刪除標點符號

[英]Remove punctuation from beginning and end of words in a string

我有一個字符串,我想刪除任何- ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,' - ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,'從單詞的開頭或結尾開始。如果單詞之間只是忽略那些單詞。

這是一個例子:

var $string = "Hello I am a string, and I am called Jack-Tack!. My -mom is Darlean.";

我想在正則表達式之后上面的文字是這樣的:

console.log("Hello I am a string and I am called Jack-Tack My mom is Darlean");

您可以使用以下事實:正則表達式中的\\b始終在單詞邊界處匹配,而\\B僅在沒有單詞邊界的情況下匹配。 你想要的只是當它的一側有一個單詞邊界而不是另一面有字邊界時才刪除這組字符。 這個正則表達式應該:

var str = "Hello I'm a string, and I am called Jack-Tack!. My -mom is Darlean.";
str = str.replace(/\b[-.,()&$#!\[\]{}"']+\B|\B[-.,()&$#!\[\]{}"']+\b/g, "");
console.log(str); // Hello I'm a string and I am called Jack-Tack My mom is Darlean

這是我剛剛創建的一個。 它可能會簡化,但它的工作原理。

"Hello I am a string, and I am called Jack-Tack!. My -mom is Darlean."
.replace(/(?:[\(\)\-&$#!\[\]{}\"\',\.]+(?:\s|$)|(?:^|\s)[\(\)\-&$#!\[\]{}\"\',\.]+)/g, ' ')
.trim();

用空字符串替換此正則表達式。

/(?<=\s)[^A-Z]+?(?=\w)|(?<=\w)[^a-z]*?(?=\s|$)/gi

//Explanation:
/
(?<=\s)[^A-Z]+?(?=\w)    //Find any non-letters preceded by a space and followed by a word
|                        //OR
(?<=\w)[^a-z]*?(?=\s|$)  //Any non-letters preceded by a work and followed by a space.
/gxi

暫無
暫無

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

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