如何在JavaScript中将长整型表达式分割成多行? [英] How to split a long regular expression into multiple lines in JavaScript?
本文介绍了如何在JavaScript中将长整型表达式分割成多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里的模式示例:
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,}))$ /;
解决方案
您可以将其转换为字符串并创建表达式通过调用 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(''));
注意:
-
RegExp
接受修饰符作为第二个参数
/ regex / g
=>new RegExp('regex','g')
将表达式文字转换为字符串时,您需要将所有反斜杠转义为在评估字符串文字时使用的反斜杠。 (见Kayo的更多细节的评论。)
I have a very long regular expression, which I wish to split into multiple lines in my JavaScript code to keep each line length 80 characters according to JSLint rules. It's just better for reading, I think. Here's pattern sample:
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,}))$/;
解决方案
You could convert it to a string and create the expression by calling 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(''));
Note:
- when converting the expression literal to a string you need to escape all backslashes as backslashes are consumed when evaluating a string literal. (See Kayo's comment for more detail.)
RegExp
accepts modifiers as a second parameter/regex/g
=>new RegExp('regex', 'g')
这篇关于如何在JavaScript中将长整型表达式分割成多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文