-2

I would like to extract a string between a (' and ',

here is what it looks like:

('I enter in {string}',

and I want to extract

I should see the menu page
I create a custom order with create your own salad
I dismiss the dietary preferences menu tooltip

These are gherkin steps in my automation framework and I've tried using

\'[^']+'

but this also returns any imports that I have in my page classes such as '../src/etc' which I don't want.

1
  • So why not /\('(.*?)',/? Commented Jul 26, 2021 at 17:05

1 Answer 1

1

You could use a capturing group and a generator like this:

const input = "('I enter in {string}', ('blbl',"

const regex = /\('([^']*)',/ig;

function* getResults(input, regex) {
  let match;

  while (match = regex.exec(input)) {
      yield match[1];
  }
}

const results = [ ...getResults(input, regex) ];

console.log(results);

Shorter solution:

const input = "('I enter in {string}', ('blbl',"

const regex = /\('([^']*)',/ig;

const results = [ ...input.matchAll(regex) ].map(([, x]) => x);

console.log(results);

Sign up to request clarification or add additional context in comments.

2 Comments

How do I capture all strings matching this regex?. I am reading from a file and there are multiple strings that I need to extract. I tried let array = fileContents.match(/('(.*)',/g); . However I am getting an array of strings such as ["('I go to the payment page',", "('I close the menu', "]
@Orbita1frame I've edited my answer with two solutions for your requirement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.