google closure - how do I break up a regular expression in JavaScript - Stack Overflow

String.prototype.is_email = function() {return this.match([a-z0-9!#$%&'*+=?^_`{|}~-]+(?:.[a-

  String.prototype.is_email = function() {
      return this.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}||org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/);
  };

I'm trying to get all my javascript files to lint under closure linter ( .html ); how do I break up a Regular Expression using the /regex/ syntax.

Line 24, E:0110: Line too long (200 characters). Found 1 errors, including 0 new errors, in 1 files (0 files OK).

  String.prototype.is_email = function() {
      return this.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}||org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/);
  };

I'm trying to get all my javascript files to lint under closure linter ( http://code.google./closure/utilities/docs/linter_howto.html ); how do I break up a Regular Expression using the /regex/ syntax.

Line 24, E:0110: Line too long (200 characters). Found 1 errors, including 0 new errors, in 1 files (0 files OK).

Share Improve this question asked Dec 12, 2010 at 0:12 MathGladiatorMathGladiator 1,2111 gold badge10 silver badges24 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You can use the RegExp(pattern, modifiers) and pass the pattern as a string. The string can be built up in small parts using concatenation.

Very hackish: add a newline in the regexp (to break the long line into smaller ones), escape that newline by prepending a \ and place a {0} directly after it to prevent it from being taken into account, ever...

var regex = /abc\
{0}def/;

regex.test("abcdef")   // true
regex.text("abc\ndef") // false

I wrote a simple function for bining regular expressions to make debugging them a little more manageable.

  var joinRegExp = function() {
    var args = Array.prototype.slice.call(arguments);
    return new RegExp(args.reduce(function(str, exp) {
      return str + exp.toString().replace(/\//g, '');
    }, ''));
  };

So you could break your expression into something like this.

var local = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+/;
var localOpt = /(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*/;
var domain = /(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+/;
var tld = /(?:[A-Z]{2}||org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/;

And then join them.

var emailPattern = joinRegExp(local, localOpt, /@/, domain, tld);

You can check out this plunk for a demo.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745088978a4610574.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信