split one line regex in a multiline regexp in perl

删除回忆录丶 提交于 2021-02-05 09:42:36

问题


I have trouble spliting my regex in multiple line. I want my regex to match the line given:

* Code "l;k""dfsakd;.*[])_lkaDald"

So I created this regex which work:

my $firstRegexpr = qr/^\s*\*\s*Code\s+\"(?<Code>((\")*[^\"]+)+)\"/x;

But now I want to split it in multiline like this(and want it to match the same thing!):

my $firstRegexpr = qr/^\s*\*\s*Code\s+\"
(?<Code>((\")*[^\"]+)+)\"/x;

I read about this, but I have trouble using it:

/
 ^\s*\*\s*Code\s+\"
 (?<Code>((\")*[^\"]+)+)\"
/x

My last question is about removing inlining variable in perl regex:

 my $firstRegexpr = qr/^\s*\*\s*Code\s+\"(?<Code>((\")*[^\"$]+)+)\"\$/x;

the character $] is matched as a variable in the regex, how to define it not as a variable?

Thanks a lot for your time and please provide explicit example.


回答1:


What the x flag does is very simply say 'ignore whitespace'.

So you no longer match 'space' characters , and instead have to use \s or similar.

So you can write:

if ( m/
        ^
        \d+\s+
        fish:\w+\s+
        $ 
      /x ) {
    print "Matched\n";
}

You can test regular expressions with various websites but one example is https://regex101.com/

So to take your example: https://regex101.com/r/eG5jY8/1

But how is yours not working?

This matches:

my $string = q{* Code "l;k""dfsakd;.*[])_lkaDald"};

my $firstRegexpr = qr/^\s*
                        \*
                       \s*
                       Code\s+
                       \"
                       (?<Code>((\")*[^\"]+)+)
                       \"
                    /x;

print "Compiled_Regex: $firstRegexpr\n";
print "Matched\n" if ( $string =~ m/$firstRegexpr/ );

And as for not having $] - there's two answers. Either: Use \ to escape it, or use \Q\E.



来源:https://stackoverflow.com/questions/31192520/split-one-line-regex-in-a-multiline-regexp-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!