删除字符串中单词开头和结尾的标点符号

Remove punctuation from beginning and end of words in a string

本文关键字:结尾 标点符号 开头 字符串 单词 删除      更新时间:2023-09-26

我有一个字符串,我想从单词的开头或结尾删除任何- ,( ,) ,& ,$ ,# ,! ,[ ,] ,{ ,} ," ,'。如果在单词之间,请忽略它们。

下面是一个例子:

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