[英]Can I break my Perl regex into multiple lines in my code?
我只是想知道我是否能夠打破我在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!"
我不知道如何使用正則表達式執行此操作,因為它不使用引號。 如果我按回車鍵,我猜它會在我的正則表達式中添加一個新行字符,使其成為錯誤。 我想做一些事情:
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
perlre(1)手冊頁說:
“/ x”修飾符本身需要更多解釋。 它告訴正則表達式解析器忽略大多數空格,這些空格既不是反斜杠也不是字符類。 您可以使用它將正則表達式分解為(略微)更易讀的部分。
您可以使用它來創建多行表達式。 例如:
/
abcde_abcde_abdcae_adafdf_ # Have some comments, too.
abscd_casdf_asdfd_....asdfaf # Here's your second line.
/x
如果匹配將包含空格,則在使用/ 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;
是的,請參閱perlre手冊頁中的/x modifier
。
使用+
符號。 這是一個例子:
push @steps, $steps[-1] +
$radial_velocity * $elapsed_time +
$orbital_velocity * ($phase + $phase_shift) -
$DRAG_COEFF * $altitude;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.