1

I want to write a regular expression in JavaScript that works unconditionally WRT the presence (or absence) of an optional substring within a repeated pattern. (In other words, I want it to work whether or not the substring is present.)

In the example below, consider the repeated pattern to begin with the string beg and end with the string end. The data I seek to extract are the strings foo, bar, baz, bat and qux. As you can see, the complication is the presence of the optional substring bat and what surrounds it.

Below is the example to solve.

Example

To see the live demo, click here.

https://regex101.com/r/jZ7sU3/1

Consider the following regular expression:

/beg(.*?)end/g

acting on the following content:

beg foo end beg bar end beg baz (bat) end beg qux end

produces the following result:

Match 1: foo

Match 2: bar

Match 3: baz (bat)

Match 4: qux

but the result I seek is as follows:

Match 1: foo

Match 2: bar

Match 3: baz

Match 4: bat

Match 5: qux

Can anyone figure out the solution?

Here is a similar question for Java.

7
  • I don't understand. You say "I seek 3 matches as follows", but then list four matches. The regexp you give refers to neither "end" nor "data". Please give an entire input string with the precise desired output. Commented Mar 28, 2016 at 3:34
  • @torazaburo: I just corrected it to read "four matches." Is that sufficient? Or do you need more clarification? Commented Mar 28, 2016 at 3:35
  • I don't understand how the presence or absence of the parentheses or the "optional" string would affect trying to retrieve things of the form data\d, if that's what you're trying to retrieve. Commented Mar 28, 2016 at 3:36
  • try regex101.com/r/jP0bP8/1 Commented Mar 28, 2016 at 3:43
  • 1
    @Mowzer checkout updated post below. regex101.com/r/jP0bP8/2 Commented Mar 28, 2016 at 3:58

1 Answer 1

1

Try following regex, it should match

/(?:beg (.*?)(?=\(|end))|\((.*?)\)/g

See Demo at regex101.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.