我只是想知道我是否能够打破我在Perl代码中使用的长正则表达式,以便将其写入多行?我只是希望任何可能在完成后查看我的代码的人都能保持可读性和紧凑性.我正在寻找与Perl中的几行分解字符串的方式类似的东西.例如:
print "This is a string that is ". #1st line
"very long, so it is on 2 lines!"; #2nd line
# prints = "This is a string that is very long, so it is on 2 lines!"
Run Code Online (Sandbox Code Playgroud)
我不知道如何使用正则表达式执行此操作,因为它不使用引号.如果我按下回车,我猜它会在我的正则表达式中添加一个新行字符,使其成为错误.我想做一些事情:
if($variable_1 = /abcde_abcde_abdcae_adafdf_ #1st regex line
abscd_casdf_asdfd_....asdfaf/){ #regex continued
# do something
} # regex looking for pattern = abcde_abcde_abdcae_adafdf_abscd_casdf_asdfd_....asdfaf
Run Code Online (Sandbox Code Playgroud)
Tod*_*obs 24
perlre(1)手册页说:
"/ x"修饰符本身需要更多解释.它告诉正则表达式解析器忽略大多数空格,这些空格既不是反斜杠也不是字符类.您可以使用它将正则表达式分解为(略微)更易读的部分.
您可以使用它来创建多行表达式.例如:
/
abcde_abcde_abdcae_adafdf_ # Have some comments, too.
abscd_casdf_asdfd_....asdfaf # Here's your second line.
/x
Run Code Online (Sandbox Code Playgroud)
如果匹配将包含空格,则在使用/ x修饰符时,需要在正则表达式中将它们显式化.例如,/foo bar baz quux/x不会按照您期望的方式匹配以空格分隔的字符串.相反,您需要以下内容:
print "true\n" if
/
foo
\s+ # You need explicit spaces...
bar
\s+ # because the modifier will...
baz
\s+ # otherwise ignore literal spaces.
quux
/x;
Run Code Online (Sandbox Code Playgroud)