正则表达式填空字符串

时间:2018-03-14 14:35:34

标签: javascript regex

我有一个已知开头和结尾的字符串,但我想只匹配未知中心。

例如,假设你知道你会有字符串说 “我今天午饭吃了_______”,你只想匹配空白。

以下是我的尝试:

^I had (.*) for lunch today$

哪个匹配整个字符串,以及组,即空白。

因此,当“我今天午餐吃披萨”时,会产生两场比赛: “我今天午餐吃披萨”和“披萨”

有没有办法只匹配空白?有没有办法获得“披萨”?或者至少将“披萨”作为第一场比赛?

3 个答案:

答案 0 :(得分:4)

你构建了一个捕获组;用它。

当您使用括号中包含的内容创建正则表达式时,在您的案例(.*?)中,您已创建了capturing group。与捕获组匹配的任何内容都将与完整匹配一起返回。

String.prototype.match()返回一个数组。它的第一个元素是完全匹配。所有后续元素都是捕获结果。由于您只有一个捕获组,因此结果为matches[1]

var sentences = [
    "I had pizza for lunch today",
    "I had hamburger for lunch today",
    "I had coconut for lunch today",
    "I had nothing for lunch today"
];

sentences.map(function(sentence) {
   console.log(sentence + " -> " + sentence.match(/^I had (.*?) for lunch today$/)[1])
})

答案 1 :(得分:2)

(?<=^I had )(.*?)(?= for lunch today$)

(?&lt; =)和(?=)在此描述:what is the difference between ?:, ?! and ?= in regex?

=&GT;

(?<=^I had ): It starts with "I had " but this is not captured.
(?= for lunch today$): It ends with " for lunch today" but this is not captured

=&GT;

/(?<=^I had )(.*?)(?= for lunch today$)/_/ 

应该有效

或者像这样,如果不支持正面观察:

/(^I had )(.*?)(?= for lunch today$)/$1_/

=&GT;我今天吃午饭了

答案 2 :(得分:0)

它不使用RegEx并且不是最漂亮的,但是如果您知道包围您想要找到的字符串的单词,这可以完美地工作。

const testString = 'I had pizza for lunch today';

const getUnknown = (str, startWord, endWord) => str.split(startWord)[1]
  .split(endWord)[0]
  .trim();

console.log(getUnknown(testString, 'had', 'for'));