Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for a fill-in-the-blank type string

I have a string with a known beginning and end, but I want to match only the unknown center.

For example, say you knew you were going to have strings which said "I had ________ for lunch today" and you only wanted to match the blank.

Here's what I have tried:

^I had (.*) for lunch today$

Which matches the entire string, and also the group, which is the blank.

So when given "I had pizza for lunch today" it produces two matches:
"I had pizza for lunch today" and "pizza"

Is there any way to only match the blank? Is there any way to just get "pizza"? Or at least get "pizza" as the first match?

like image 577
MMAdams Avatar asked Mar 14 '18 14:03

MMAdams


2 Answers

You constructed a capturing group; use it.

When you create a regular expression with something wrapped in parentheses, in your case (.*?), you have created a capturing group. Whatever is matched by capturing groups will be returned alongside the full match.

String.prototype.match() returns an array. Its first element is the full match. All subsequent elements are captured results. Since you only have one capturing group, the result is 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])
})
like image 120
revo Avatar answered Oct 09 '22 07:10

revo


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

(?<=) and (?=) are described here: what is the difference between ?:, ?! and ?= in regex?

=>

(?<=^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

=>

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

should work

Or like that, if positive look behind is not supported:

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

=> I had _ for lunch today

like image 31
D. Braun Avatar answered Oct 09 '22 07:10

D. Braun