正则表达式:字符串匹配(包括标点符号) [英] Regex: String match including punctuation
本文介绍了正则表达式:字符串匹配(包括标点符号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从另一个问题,我使用此表达式来匹配句子中的单词:
From another question, I have this expression to match words in a sentence:
var sentence = "Exclamation! Question? Full stop. Ellipsis...";
console.log(sentence.toLowerCase().match(/\w+(?:'\w+)*/g));
它完美地工作.但是,现在我正在寻找一种分别匹配感叹号,问号和句号的方法.结果应如下所示:
It works perfectly. However, now I am looking for a way to match exclamation marks, question marks, and full stops separately. The result should look like this:
[
"exclamation",
"!",
"question",
"?",
"full",
"stop",
".",
"ellipsis",
"."
]
仅匹配省略号中的一个点,而不是分别匹配所有三个点.
Only matching one dot from the ellipsis, not all three dots separately.
任何帮助将不胜感激!
推荐答案
使用单词边界仅从省略号返回一个点怎么样?
How about using a word boundary to only return one dot from the ellipsis?
var sentence = "Exclamation! Question? Full stop. Ellipsis...";
console.log(sentence.toLowerCase().match(/[a-z]+(?:'[a-z]+)*|\b[!?.]/g));
或否定的前瞻:
var sentence = "Exclamation! Question? Full stop. Ellipsis...";
console.log(sentence.toLowerCase().match(/[a-z]+(?:'[a-z]+)*|[!?.](?![!?.])/g));
在您对场景扩展进行了评论之后,向后隐式看似有效.
After your commented scenario extension, a negative lookbehind seems to be effective.
var sentence = "You're \"Pregnant\"??? How'd This Happen?! The vasectomy YOUR 1 job. Let's \"talk this out\"...";
console.log(sentence.toLowerCase().match(/[a-z\d]+(?:'[a-z\d]+)*|(?<![!?.])[!?.]/g));
这篇关于正则表达式:字符串匹配(包括标点符号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文