如何在JavaScript中将长正则表达式拆分为多行?

时间:2012-09-07 11:17:11

标签: javascript regex jslint expression readability

我有一个非常长的正则表达式,我想在我的JavaScript代码中拆分成多行,以根据JSLint规则保持每行长度为80个字符。我认为这对阅读来说更好。 这是模式样本:

var pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

11 个答案:

答案 0 :(得分:101)

您可以将其转换为字符串并通过调用new RegExp()来创建表达式:

var myRE = new RegExp (['^(([^<>()[\]\\.,;:\\s@\"]+(\\.[^<>(),[\]\\.,;:\\s@\"]+)*)',
                        '|(\\".+\\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.',
                        '[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\\.)+',
                        '[a-zA-Z]{2,}))$'].join(''));

注意:

  1. 表达式文字转换为字符串时,需要转义所有反斜杠,因为在评估字符串文字时会消耗反斜杠。 (有关详细信息,请参阅Kayo的评论。)
  2. RegExp接受修饰符作为第二个参数

    /regex/g =&gt; new RegExp('regex', 'g')

  3. [添加ES20xx (标记模板)]

    在ES20xx中,您可以使用tagged templates。请参阅代码段。

    注意:

    • 这里的缺点是您不能在正则表达式字符串中使用普通空格(始终使用\s\s+\s{1,x}\t,{{1}等等)。

    \n

答案 1 :(得分:94)

扩展@KooiInc答案,您可以避免使用source对象的RegExp属性手动转义每个特殊字符。

示例:

var urlRegex= new RegExp(''
  + /(?:(?:(https?|ftp):)?\/\/)/.source     // protocol
  + /(?:([^:\n\r]+):([^@\n\r]+)@)?/.source  // user:pass
  + /(?:(?:www\.)?([^\/\n\r]+))/.source     // domain
  + /(\/[^?\n\r]+)?/.source                 // request
  + /(\?[^#\n\r]*)?/.source                 // query
  + /(#?[^\n\r]*)?/.source                  // anchor
);

或者如果您想避免重复.source属性,可以使用Array.map()函数执行此操作:

var urlRegex= new RegExp([
  /(?:(?:(https?|ftp):)?\/\/)/      // protocol
  ,/(?:([^:\n\r]+):([^@\n\r]+)@)?/  // user:pass
  ,/(?:(?:www\.)?([^\/\n\r]+))/     // domain
  ,/(\/[^?\n\r]+)?/                 // request
  ,/(\?[^#\n\r]*)?/                 // query
  ,/(#?[^\n\r]*)?/                  // anchor
].map(function(r) {return r.source}).join(''));

在ES6中,地图功能可以简化为: .map(r => r.source)

答案 2 :(得分:22)

new RegExp中使用字符串很尴尬,因为您必须转义所有反斜杠。您可以编写较小的正则表达式并将它们连接起来。

让我们分开这个正则表达式

/^foo(.*)\bar$/

我们将使用一个函数来使事情更美好

function multilineRegExp(regs, options) {
    return new RegExp(regs.map(
        function(reg){ return reg.source; }
    ).join(''), options);
}

现在让我们摇滚

var r = multilineRegExp([
     /^foo/,  // we can add comments too
     /(.*)/,
     /\bar$/
]);

由于它有成本,尝试只构建一次真正的正则表达式然后使用它。

答案 3 :(得分:7)

由于template literals的奇妙世界,您现在可以在ES6中编写大型的,多行的,注释良好的,甚至语义上嵌套的正则表达式。

//build regexes without worrying about
// - double-backslashing
// - adding whitespace for readability
// - adding in comments
let clean = (piece) => (piece
    .replace(/((^|\n)(?:[^\/\\]|\/[^*\/]|\\.)*?)\s*\/\*(?:[^*]|\*[^\/])*(\*\/|)/g, '$1')
    .replace(/((^|\n)(?:[^\/\\]|\/[^\/]|\\.)*?)\s*\/\/[^\n]*/g, '$1')
    .replace(/\n\s*/g, '')
);
window.regex = ({raw}, ...interpolations) => (
    new RegExp(interpolations.reduce(
        (regex, insert, index) => (regex + insert + clean(raw[index + 1])),
        clean(raw[0])
    ))
);

使用此方法,您现在可以编写如下正则表达式:

let re = regex`I'm a special regex{3} //with a comment!`;

输出

/I'm a special regex{3}/

Or what about multiline?

'123hello'
    .match(regex`
        //so this is a regex

        //here I am matching some numbers
        (\d+)

        //Oh! See how I didn't need to double backslash that \d?
        ([a-z]{1,3}) /*note to self, this is group #2*/
    `)
    [2]

输出hel,整齐了!
“如果我需要实际搜索换行符怎么办?”然后傻傻地使用\n吧!
使用我的Firefox和Chrome。


好吧,“稍微复杂一点?”
当然,here's a piece of an object destructuring JS parser I was working on

regex`^\s*
    (
        //closing the object
        (\})|

        //starting from open or comma you can...
        (?:[,{]\s*)(?:
            //have a rest operator
            (\.\.\.)
            |
            //have a property key
            (
                //a non-negative integer
                \b\d+\b
                |
                //any unencapsulated string of the following
                \b[A-Za-z$_][\w$]*\b
                |
                //a quoted string
                //this is #5!
                ("|')(?:
                    //that contains any non-escape, non-quote character
                    (?!\5|\\).
                    |
                    //or any escape sequence
                    (?:\\.)
                //finished by the quote
                )*\5
            )
            //after a property key, we can go inside
            \s*(:|)
      |
      \s*(?={)
        )
    )
    ((?:
        //after closing we expect either
        // - the parent's comma/close,
        // - or the end of the string
        \s*(?:[,}\]=]|$)
        |
        //after the rest operator we expect the close
        \s*\}
        |
        //after diving into a key we expect that object to open
        \s*[{[:]
        |
        //otherwise we saw only a key, we now expect a comma or close
        \s*[,}{]
    ).*)
$`

它输出/^\s*((\})|(?:[,{]\s*)(?:(\.\.\.)|(\b\d+\b|\b[A-Za-z$_][\w$]*\b|("|')(?:(?!\5|\\).|(?:\\.))*\5)\s*(:|)|\s*(?={)))((?:\s*(?:[,}\]=]|$)|\s*\}|\s*[{[:]|\s*[,}{]).*)$/

并通过一个演示运行它?

let input = '{why, hello, there, "you   huge \\"", 17, {big,smelly}}';
for (
    let parsed;
    parsed = input.match(r);
    input = parsed[parsed.length - 1]
) console.log(parsed[1]);

成功输出

{why
, hello
, there
, "you   huge \""
, 17
,
{big
,smelly
}
}

请注意已成功捕获带引号的字符串。
我在Chrome和Firefox上测试过,效果不错!

如果为curious you can checkout what I was doingits demonstration
尽管它仅在Chrome上有效,但因为Firefox不支持反向引用或命名组。因此请注意,此答案中给出的示例实际上是一个绝望的版本,可能容易被欺骗以接受无效的字符串。

答案 4 :(得分:4)

上面的正则表达式缺少一些不能正常工作的黑色斜线。所以,我编辑了正则表达式。请考虑这个正则表达式,99.99%用于电子邮件验证。

curl -X POST https://api.dropboxapi.com/2/files/delete \
    --header "Authorization: Bearer ACCESS_TOKEN" \
    --header "Content-Type: application/json" \
    --data "{\"path\": \"/Homework/math/Prime_Numbers.txt\"}"

答案 5 :(得分:1)

要避免使用数组join,您还可以使用以下语法:

var pattern = new RegExp('^(([^<>()[\]\\.,;:\s@\"]+' +
  '(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@' +
  '((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|' +
  '(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$');

答案 6 :(得分:1)

这里有很好的答案,但是为了完整起见,应该使用prototype chain来提及Javascript继承的核心功能。这样的东西说明了这个想法:

RegExp.prototype.append = function(re) {
  return new RegExp(this.source + re.source, this.flags);
};

let regex = /[a-z]/g
.append(/[A-Z]/)
.append(/[0-9]/);

console.log(regex); //=> /[a-z][A-Z][0-9]/g

答案 7 :(得分:0)

就个人而言,我会选择一个不那么复杂的正则表达式:

/\S+@\S+\.\S+/

当然,它比你当前的模式更准确 ,但是你想要完成什么?您是否试图捕获用户可能输入的意外错误,或者您是否担心用户可能会尝试输入无效地址?如果是第一个,我会选择一个更简单的模式。如果是后者,通过回复发送到该地址的电子邮件进行的一些验证可能是更好的选择。

但是,如果你想使用你当前的模式,通过从较小的子模式构建它(IMO)将更容易阅读(和维护!),如下所示:

var box1 = "([^<>()[\]\\\\.,;:\s@\"]+(\\.[^<>()[\\]\\\\.,;:\s@\"]+)*)";
var box2 = "(\".+\")";

var host1 = "(\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])";
var host2 = "(([a-zA-Z\-0-9]+\\.)+[a-zA-Z]{2,})";

var regex = new RegExp("^(" + box1 + "|" + box2 + ")@(" + host1 + "|" + host2 + ")$");

答案 8 :(得分:0)

您可以简单地使用字符串操作。

var pattenString = "^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|"+
"(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|"+
"(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";
var patten = new RegExp(pattenString);

答案 9 :(得分:0)

我试图通过封装所有内容并实现对拆分捕获组和字符集的支持来改善korun的答案-使这种方法更加通用。

要使用此代码段,您需要调用可变参数combineRegex,其参数是您需要组合的正则表达式对象。可以在底部找到它的实现。

虽然不能那样直接拆分捕获组,因为捕获组的某些部分仅带有一个括号。您的浏览器将因异常而失败。

相反,我只是将捕获组的内容传递给数组。当combineRegex遇到数组时,括号会自动添加。

此外,量词还需要遵循一些规定。如果由于某种原因正则表达式需要在量词前进行拆分,则需要添加一对括号。这些将被自动删除。关键是空的捕获组几乎没有用,因此量词有一定的参考意义。可以将相同的方法用于非捕获组(/(?:abc)/变为[/()?:abc/])之类的事情。

最好用一个简单的例子来说明:

var regex = /abcd(efghi)+jkl/;

将成为:

var regex = combineRegex(
    /ab/,
    /cd/,
    [
        /ef/,
        /ghi/
    ],
    /()+jkl/    // Note the added '()' in front of '+'
);

如果必须拆分字符集,则可以使用对象({"":[regex1, regex2, ...]})而不是数组([regex1, regex2, ...])。密钥的内容可以是任何内容,只要对象仅包含一个密钥即可。请注意,如果第一个字符可以解释为量词,则必须使用()作为伪开头,而不是]。即/[+?]/成为{"":[/]+?/]}

以下是代码段和更完整的示例:

function combineRegexStr(dummy, ...regex)
{
    return regex.map(r => {
        if(Array.isArray(r))
            return "("+combineRegexStr(dummy, ...r).replace(dummy, "")+")";
        else if(Object.getPrototypeOf(r) === Object.getPrototypeOf({}))
            return "["+combineRegexStr(/^\]/, ...(Object.entries(r)[0][1]))+"]";
        else 
            return r.source.replace(dummy, "");
    }).join("");
}
function combineRegex(...regex)
{
    return new RegExp(combineRegexStr(/^\(\)/, ...regex));
}

//Usage:
//Original:
console.log(/abcd(?:ef[+A-Z0-9]gh)+$/.source);
//Same as:
console.log(
  combineRegex(
    /ab/,
    /cd/,
    [
      /()?:ef/,
      {"": [/]+A-Z/, /0-9/]},
      /gh/
    ],
    /()+$/
  ).source
);

答案 10 :(得分:0)

@Hashbrown出色的answer使我步入正轨。这是我的版本,也受此blog的启发。

function regexp(...args) {
  function cleanup(string) {
    // remove whitespace, single and multi-line comments
    return string.replace(/\s+|\/\/.*|\/\*[\s\S]*?\*\//g, '');
  }

  function escape(string) {
    // escape regular expression
    return string.replace(/[-.*+?^${}()|[\]\\]/g, '\\$&');
  }

  function create(flags, strings, ...values) {
    let pattern = '';
    for (let i = 0; i < values.length; ++i) {
      pattern += cleanup(strings.raw[i]);  // strings are cleaned up
      pattern += escape(values[i]);        // values are escaped
    }
    pattern += cleanup(strings.raw[values.length]);
    return RegExp(pattern, flags);
  }

  if (Array.isArray(args[0])) {
    // used as a template tag (no flags)
    return create('', ...args);
  }

  // used as a function (with flags)
  return create.bind(void 0, args[0]);
}

像这样使用它:

regexp('i')`
  //so this is a regex

  //here I am matching some numbers
  (\d+)

  //Oh! See how I didn't need to double backslash that \d?
  ([a-z]{1,3}) /*note to self, this is group #2*/
`

要创建此RegExp对象:

/(\d+)([a-z]{1,3})/i