Find your people. Pick a challenge. Ship something real. The CreatorCon Hackathon is coming to the Community Pavilion for one epic night. Every skill level, every role welcome. Join us on May 5th and learn more here.

Regex - Matching across multiple lines

Jamsta1912
Tera Guru

Hi everyone,

I have a question about regex in javascript. I'm trying to pick out the part of a string between two key phrases / characters, across multiple lines.

If I run this background script:

var x= 'abcdefg';

var myreg = /b.*e/i;

gs.print('myreg : ' + x.match(myreg));

I get this:

*** Script: myreg : bcde

That's simple and makes sense to me: it's picking out the text that starts with b and ends with e, with any number of characters intbetween excluding line breaks.

But what should the regular expression look like if I wanted to match on a string that starts with b and ends with e, with any number of characters inbetween including line breaks?

I tried this:

var x= 'abcdefg';

var myreg = /b(.|\n|\r)*e/i;

gs.print('myreg : ' + x.match(myreg));

and instead of 'bcde' I get:

*** Script: myreg : bcde,d

So then I tried this:

var x= 'abcdefg';

var myreg = /b((.|\n|\r)*)e/i;

gs.print('myreg : ' + x.match(myreg));

and I get:

*** Script: myreg : bcde,cd,d

So in those last two cases I'm getting multiple matches returned, which I don't understand . Can anyone explain what's happening there? And, what's the best practice way to match on text between two phrases / characters, allowing there to be line breaks inbetween?

Thank you

Jamie

2 REPLIES 2

divya mishra
Kilo Sage

Hey Jamie,



The first expression looks good to me(tested) It allowed me to get characters between b and e including line breaks.




post me your feedback


Please Hit ✅Correct, ��Helpful, or ��Like depending on the impact of the response


Have a lovely day ahead




Regards,


Divya Mishra


Hi Divya,



The first script doesn't work across line breaks, as the dot represents any character except line breaks.


So, for instance this:



var x= 'abcd\nefg';


var myreg = /b.*e/i;


gs.print('myreg : ' + x.match(myreg));



returns



*** Script: myreg : null



But you may have meant my first alternative script. That one though, returns an array of more than one match.


Any other thoughts?



Jamie.