正则表达式:字符串匹配(包括标点符号)

时间:2018-07-29 01:55:22

标签: javascript regex string replace match

From another question,我有一个表达式可以匹配句子中的单词:

var sentence = "Exclamation! Question? Full stop. Ellipsis...";
console.log(sentence.toLowerCase().match(/\w+(?:'\w+)*/g));

它完美地工作。但是,现在我正在寻找一种分别匹配感叹号,问号和句号的方法。结果应如下所示:

[
  "exclamation",
  "!",
  "question",
  "?",
  "full",
  "stop",
  ".",
  "ellipsis",
  "."
]

仅匹配省略号中的一个点,而不是分别匹配所有三个点。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:4)

尝试以下代码

var sentence = "Exclamation! Question? Full stop. Ellipsis...";
console.log(sentence.toLowerCase().match(/[?!.]|\w+/g));

如果只需要一个点,可以使用---

var sentence = "Exclamation!!! Question??? Full stop. Ellipsis...";

var arr = sentence.toLowerCase().match(/[?]+|[!]+|[.]+|\w+/g);
arr = arr.map(function(item){
	return item.replace(/(.)\1+/g, "$1");
})

console.log(arr);

答案 1 :(得分:2)

使用单词边界仅从省略号返回一个点怎么样?

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));

在您对场景扩展进行了评论之后,向后隐式看似有效。

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));