How can I place newlines in my regex to make it more readable? [duplicate]











up vote
3
down vote

favorite













This question already has an answer here:




  • Commenting Regular Expressions

    3 answers




I have a really long email-matching regex in JavasScript that I would like to break into multiple lines without changing the regex functionality. I know some regex engines offer a way to insert newlines for readability, is there a way to do that in JS?










share|improve this question













marked as duplicate by Wiktor Stribiżew javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 22 at 9:30


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • Can you provide the regex?
    – ibrahim mahrir
    Nov 22 at 0:01






  • 1




    I mean I could but it shouldn't make any difference to the question, it's arbitrary. It applies equally to all regexes. But it's the email-matching regex from the MDN docs. And yeah that's true I could do it that way, but it's not really exactly what I'm looking for here and more of a work-around.
    – Aerovistae
    Nov 22 at 0:06

















up vote
3
down vote

favorite













This question already has an answer here:




  • Commenting Regular Expressions

    3 answers




I have a really long email-matching regex in JavasScript that I would like to break into multiple lines without changing the regex functionality. I know some regex engines offer a way to insert newlines for readability, is there a way to do that in JS?










share|improve this question













marked as duplicate by Wiktor Stribiżew javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 22 at 9:30


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • Can you provide the regex?
    – ibrahim mahrir
    Nov 22 at 0:01






  • 1




    I mean I could but it shouldn't make any difference to the question, it's arbitrary. It applies equally to all regexes. But it's the email-matching regex from the MDN docs. And yeah that's true I could do it that way, but it's not really exactly what I'm looking for here and more of a work-around.
    – Aerovistae
    Nov 22 at 0:06















up vote
3
down vote

favorite









up vote
3
down vote

favorite












This question already has an answer here:




  • Commenting Regular Expressions

    3 answers




I have a really long email-matching regex in JavasScript that I would like to break into multiple lines without changing the regex functionality. I know some regex engines offer a way to insert newlines for readability, is there a way to do that in JS?










share|improve this question














This question already has an answer here:




  • Commenting Regular Expressions

    3 answers




I have a really long email-matching regex in JavasScript that I would like to break into multiple lines without changing the regex functionality. I know some regex engines offer a way to insert newlines for readability, is there a way to do that in JS?





This question already has an answer here:




  • Commenting Regular Expressions

    3 answers








javascript regex






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 at 23:59









Aerovistae

16.5k2895160




16.5k2895160




marked as duplicate by Wiktor Stribiżew javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 22 at 9:30


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by Wiktor Stribiżew javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 22 at 9:30


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • Can you provide the regex?
    – ibrahim mahrir
    Nov 22 at 0:01






  • 1




    I mean I could but it shouldn't make any difference to the question, it's arbitrary. It applies equally to all regexes. But it's the email-matching regex from the MDN docs. And yeah that's true I could do it that way, but it's not really exactly what I'm looking for here and more of a work-around.
    – Aerovistae
    Nov 22 at 0:06




















  • Can you provide the regex?
    – ibrahim mahrir
    Nov 22 at 0:01






  • 1




    I mean I could but it shouldn't make any difference to the question, it's arbitrary. It applies equally to all regexes. But it's the email-matching regex from the MDN docs. And yeah that's true I could do it that way, but it's not really exactly what I'm looking for here and more of a work-around.
    – Aerovistae
    Nov 22 at 0:06


















Can you provide the regex?
– ibrahim mahrir
Nov 22 at 0:01




Can you provide the regex?
– ibrahim mahrir
Nov 22 at 0:01




1




1




I mean I could but it shouldn't make any difference to the question, it's arbitrary. It applies equally to all regexes. But it's the email-matching regex from the MDN docs. And yeah that's true I could do it that way, but it's not really exactly what I'm looking for here and more of a work-around.
– Aerovistae
Nov 22 at 0:06






I mean I could but it shouldn't make any difference to the question, it's arbitrary. It applies equally to all regexes. But it's the email-matching regex from the MDN docs. And yeah that's true I could do it that way, but it's not really exactly what I'm looking for here and more of a work-around.
– Aerovistae
Nov 22 at 0:06














1 Answer
1






active

oldest

votes

















up vote
4
down vote



accepted










There's no built-in way to accomplish such a thing, but it's not hard to accomplish it yourself. You can use a template literal with String.raw, which will allow you to use newlines in the regex string, without having to double-escape backslashes, and then you can replace all newlines with the empty string before passing it to new RegExp:






const patternStr = String.raw`^
[fg]oo
=
war`;
const pattern = new RegExp(patternStr.replace(/n/g, ''));
console.log(pattern.test('foo=bar'));
console.log(pattern.test('goo=bar'));
console.log(pattern.test('hoo=bar'));





You can use a similar technique to allow comments as well:






const patternStr = String.raw`
^ // Match the beginning of the string
[fg]oo // Match either f or g, followed by oo
= // Match an equals sign
war // Match a word character, followed by "ar"
`;
const pattern = new RegExp(
patternStr.replace(/(?: *//.*)?n/g, '')
);
console.log(pattern.test('foo=bar'));
console.log(pattern.test('goo=bar'));
console.log(pattern.test('hoo=bar'));





The (?: *//.*)?n pattern means:



(?: *//.*)? - An optional group of zero or more spaces, followed by //, followed by non-newline characters



n - followed by a newline



Of course, this means it'll be impossible to write // as is in the regex, but that's OK, you can just escape forward slashes just like you do with regular expression literals (it'll be parsed by the RegExp constructor as an unnecessary escape character):






const patternStr = String.raw`
^ // Match the beginning of the string
// // Match two literal forward slashes
`;
const pattern = new RegExp(
patternStr.replace(/(?: *//.*)?n/g, '')
);
console.log(pattern.test('//foo'));
console.log(pattern.test('foo'));





Another way would be to allow literal //s in the template literal by, when matching the comment // <text> n, make sure that <text> doesn't have any //s in it. This would mean that only the final // on a line would be parsed as a comment, allowing you to use //s earlier on the line, without escaping, without problems, by using (?:(?!//).)* instead of .*:






const patternStr = String.raw`
^ // Match the beginning of the string
// // Match two literal forward slashes
`;
const pattern = new RegExp(
patternStr.replace(/(?: *//(?:(?!//).)*)?n/g, '')
);
console.log(pattern.test('//foo'));
console.log(pattern.test('foo'));





Of course, this will mean that //s will only be parsed as actual double-forward-slashes in the regex if there's another // farther right in the line. (If there isn't another // later, you'll have to use // instead)






share|improve this answer






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    4
    down vote



    accepted










    There's no built-in way to accomplish such a thing, but it's not hard to accomplish it yourself. You can use a template literal with String.raw, which will allow you to use newlines in the regex string, without having to double-escape backslashes, and then you can replace all newlines with the empty string before passing it to new RegExp:






    const patternStr = String.raw`^
    [fg]oo
    =
    war`;
    const pattern = new RegExp(patternStr.replace(/n/g, ''));
    console.log(pattern.test('foo=bar'));
    console.log(pattern.test('goo=bar'));
    console.log(pattern.test('hoo=bar'));





    You can use a similar technique to allow comments as well:






    const patternStr = String.raw`
    ^ // Match the beginning of the string
    [fg]oo // Match either f or g, followed by oo
    = // Match an equals sign
    war // Match a word character, followed by "ar"
    `;
    const pattern = new RegExp(
    patternStr.replace(/(?: *//.*)?n/g, '')
    );
    console.log(pattern.test('foo=bar'));
    console.log(pattern.test('goo=bar'));
    console.log(pattern.test('hoo=bar'));





    The (?: *//.*)?n pattern means:



    (?: *//.*)? - An optional group of zero or more spaces, followed by //, followed by non-newline characters



    n - followed by a newline



    Of course, this means it'll be impossible to write // as is in the regex, but that's OK, you can just escape forward slashes just like you do with regular expression literals (it'll be parsed by the RegExp constructor as an unnecessary escape character):






    const patternStr = String.raw`
    ^ // Match the beginning of the string
    // // Match two literal forward slashes
    `;
    const pattern = new RegExp(
    patternStr.replace(/(?: *//.*)?n/g, '')
    );
    console.log(pattern.test('//foo'));
    console.log(pattern.test('foo'));





    Another way would be to allow literal //s in the template literal by, when matching the comment // <text> n, make sure that <text> doesn't have any //s in it. This would mean that only the final // on a line would be parsed as a comment, allowing you to use //s earlier on the line, without escaping, without problems, by using (?:(?!//).)* instead of .*:






    const patternStr = String.raw`
    ^ // Match the beginning of the string
    // // Match two literal forward slashes
    `;
    const pattern = new RegExp(
    patternStr.replace(/(?: *//(?:(?!//).)*)?n/g, '')
    );
    console.log(pattern.test('//foo'));
    console.log(pattern.test('foo'));





    Of course, this will mean that //s will only be parsed as actual double-forward-slashes in the regex if there's another // farther right in the line. (If there isn't another // later, you'll have to use // instead)






    share|improve this answer



























      up vote
      4
      down vote



      accepted










      There's no built-in way to accomplish such a thing, but it's not hard to accomplish it yourself. You can use a template literal with String.raw, which will allow you to use newlines in the regex string, without having to double-escape backslashes, and then you can replace all newlines with the empty string before passing it to new RegExp:






      const patternStr = String.raw`^
      [fg]oo
      =
      war`;
      const pattern = new RegExp(patternStr.replace(/n/g, ''));
      console.log(pattern.test('foo=bar'));
      console.log(pattern.test('goo=bar'));
      console.log(pattern.test('hoo=bar'));





      You can use a similar technique to allow comments as well:






      const patternStr = String.raw`
      ^ // Match the beginning of the string
      [fg]oo // Match either f or g, followed by oo
      = // Match an equals sign
      war // Match a word character, followed by "ar"
      `;
      const pattern = new RegExp(
      patternStr.replace(/(?: *//.*)?n/g, '')
      );
      console.log(pattern.test('foo=bar'));
      console.log(pattern.test('goo=bar'));
      console.log(pattern.test('hoo=bar'));





      The (?: *//.*)?n pattern means:



      (?: *//.*)? - An optional group of zero or more spaces, followed by //, followed by non-newline characters



      n - followed by a newline



      Of course, this means it'll be impossible to write // as is in the regex, but that's OK, you can just escape forward slashes just like you do with regular expression literals (it'll be parsed by the RegExp constructor as an unnecessary escape character):






      const patternStr = String.raw`
      ^ // Match the beginning of the string
      // // Match two literal forward slashes
      `;
      const pattern = new RegExp(
      patternStr.replace(/(?: *//.*)?n/g, '')
      );
      console.log(pattern.test('//foo'));
      console.log(pattern.test('foo'));





      Another way would be to allow literal //s in the template literal by, when matching the comment // <text> n, make sure that <text> doesn't have any //s in it. This would mean that only the final // on a line would be parsed as a comment, allowing you to use //s earlier on the line, without escaping, without problems, by using (?:(?!//).)* instead of .*:






      const patternStr = String.raw`
      ^ // Match the beginning of the string
      // // Match two literal forward slashes
      `;
      const pattern = new RegExp(
      patternStr.replace(/(?: *//(?:(?!//).)*)?n/g, '')
      );
      console.log(pattern.test('//foo'));
      console.log(pattern.test('foo'));





      Of course, this will mean that //s will only be parsed as actual double-forward-slashes in the regex if there's another // farther right in the line. (If there isn't another // later, you'll have to use // instead)






      share|improve this answer

























        up vote
        4
        down vote



        accepted







        up vote
        4
        down vote



        accepted






        There's no built-in way to accomplish such a thing, but it's not hard to accomplish it yourself. You can use a template literal with String.raw, which will allow you to use newlines in the regex string, without having to double-escape backslashes, and then you can replace all newlines with the empty string before passing it to new RegExp:






        const patternStr = String.raw`^
        [fg]oo
        =
        war`;
        const pattern = new RegExp(patternStr.replace(/n/g, ''));
        console.log(pattern.test('foo=bar'));
        console.log(pattern.test('goo=bar'));
        console.log(pattern.test('hoo=bar'));





        You can use a similar technique to allow comments as well:






        const patternStr = String.raw`
        ^ // Match the beginning of the string
        [fg]oo // Match either f or g, followed by oo
        = // Match an equals sign
        war // Match a word character, followed by "ar"
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//.*)?n/g, '')
        );
        console.log(pattern.test('foo=bar'));
        console.log(pattern.test('goo=bar'));
        console.log(pattern.test('hoo=bar'));





        The (?: *//.*)?n pattern means:



        (?: *//.*)? - An optional group of zero or more spaces, followed by //, followed by non-newline characters



        n - followed by a newline



        Of course, this means it'll be impossible to write // as is in the regex, but that's OK, you can just escape forward slashes just like you do with regular expression literals (it'll be parsed by the RegExp constructor as an unnecessary escape character):






        const patternStr = String.raw`
        ^ // Match the beginning of the string
        // // Match two literal forward slashes
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//.*)?n/g, '')
        );
        console.log(pattern.test('//foo'));
        console.log(pattern.test('foo'));





        Another way would be to allow literal //s in the template literal by, when matching the comment // <text> n, make sure that <text> doesn't have any //s in it. This would mean that only the final // on a line would be parsed as a comment, allowing you to use //s earlier on the line, without escaping, without problems, by using (?:(?!//).)* instead of .*:






        const patternStr = String.raw`
        ^ // Match the beginning of the string
        // // Match two literal forward slashes
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//(?:(?!//).)*)?n/g, '')
        );
        console.log(pattern.test('//foo'));
        console.log(pattern.test('foo'));





        Of course, this will mean that //s will only be parsed as actual double-forward-slashes in the regex if there's another // farther right in the line. (If there isn't another // later, you'll have to use // instead)






        share|improve this answer














        There's no built-in way to accomplish such a thing, but it's not hard to accomplish it yourself. You can use a template literal with String.raw, which will allow you to use newlines in the regex string, without having to double-escape backslashes, and then you can replace all newlines with the empty string before passing it to new RegExp:






        const patternStr = String.raw`^
        [fg]oo
        =
        war`;
        const pattern = new RegExp(patternStr.replace(/n/g, ''));
        console.log(pattern.test('foo=bar'));
        console.log(pattern.test('goo=bar'));
        console.log(pattern.test('hoo=bar'));





        You can use a similar technique to allow comments as well:






        const patternStr = String.raw`
        ^ // Match the beginning of the string
        [fg]oo // Match either f or g, followed by oo
        = // Match an equals sign
        war // Match a word character, followed by "ar"
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//.*)?n/g, '')
        );
        console.log(pattern.test('foo=bar'));
        console.log(pattern.test('goo=bar'));
        console.log(pattern.test('hoo=bar'));





        The (?: *//.*)?n pattern means:



        (?: *//.*)? - An optional group of zero or more spaces, followed by //, followed by non-newline characters



        n - followed by a newline



        Of course, this means it'll be impossible to write // as is in the regex, but that's OK, you can just escape forward slashes just like you do with regular expression literals (it'll be parsed by the RegExp constructor as an unnecessary escape character):






        const patternStr = String.raw`
        ^ // Match the beginning of the string
        // // Match two literal forward slashes
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//.*)?n/g, '')
        );
        console.log(pattern.test('//foo'));
        console.log(pattern.test('foo'));





        Another way would be to allow literal //s in the template literal by, when matching the comment // <text> n, make sure that <text> doesn't have any //s in it. This would mean that only the final // on a line would be parsed as a comment, allowing you to use //s earlier on the line, without escaping, without problems, by using (?:(?!//).)* instead of .*:






        const patternStr = String.raw`
        ^ // Match the beginning of the string
        // // Match two literal forward slashes
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//(?:(?!//).)*)?n/g, '')
        );
        console.log(pattern.test('//foo'));
        console.log(pattern.test('foo'));





        Of course, this will mean that //s will only be parsed as actual double-forward-slashes in the regex if there's another // farther right in the line. (If there isn't another // later, you'll have to use // instead)






        const patternStr = String.raw`^
        [fg]oo
        =
        war`;
        const pattern = new RegExp(patternStr.replace(/n/g, ''));
        console.log(pattern.test('foo=bar'));
        console.log(pattern.test('goo=bar'));
        console.log(pattern.test('hoo=bar'));





        const patternStr = String.raw`^
        [fg]oo
        =
        war`;
        const pattern = new RegExp(patternStr.replace(/n/g, ''));
        console.log(pattern.test('foo=bar'));
        console.log(pattern.test('goo=bar'));
        console.log(pattern.test('hoo=bar'));





        const patternStr = String.raw`
        ^ // Match the beginning of the string
        [fg]oo // Match either f or g, followed by oo
        = // Match an equals sign
        war // Match a word character, followed by "ar"
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//.*)?n/g, '')
        );
        console.log(pattern.test('foo=bar'));
        console.log(pattern.test('goo=bar'));
        console.log(pattern.test('hoo=bar'));





        const patternStr = String.raw`
        ^ // Match the beginning of the string
        [fg]oo // Match either f or g, followed by oo
        = // Match an equals sign
        war // Match a word character, followed by "ar"
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//.*)?n/g, '')
        );
        console.log(pattern.test('foo=bar'));
        console.log(pattern.test('goo=bar'));
        console.log(pattern.test('hoo=bar'));





        const patternStr = String.raw`
        ^ // Match the beginning of the string
        // // Match two literal forward slashes
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//.*)?n/g, '')
        );
        console.log(pattern.test('//foo'));
        console.log(pattern.test('foo'));





        const patternStr = String.raw`
        ^ // Match the beginning of the string
        // // Match two literal forward slashes
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//.*)?n/g, '')
        );
        console.log(pattern.test('//foo'));
        console.log(pattern.test('foo'));





        const patternStr = String.raw`
        ^ // Match the beginning of the string
        // // Match two literal forward slashes
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//(?:(?!//).)*)?n/g, '')
        );
        console.log(pattern.test('//foo'));
        console.log(pattern.test('foo'));





        const patternStr = String.raw`
        ^ // Match the beginning of the string
        // // Match two literal forward slashes
        `;
        const pattern = new RegExp(
        patternStr.replace(/(?: *//(?:(?!//).)*)?n/g, '')
        );
        console.log(pattern.test('//foo'));
        console.log(pattern.test('foo'));






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 22 at 0:28

























        answered Nov 22 at 0:08









        CertainPerformance

        69.7k143453




        69.7k143453















            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks