繁体   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