【问题标题】:Removing starting and ending tags from a string in Perl从 Perl 中的字符串中删除开始和结束标签
【发布时间】:2014-09-05 12:58:33
【问题描述】:

我有一个这样的字符串:

<script>This String may contain other JS tags in between </script>

我的要求是从字符串中删除开始和结束脚本标签,如果字符串之间有其他标签,则不应删除。

如何在 Perl 中做到这一点?

【问题讨论】:

标签: javascript regex perl mason


【解决方案1】:

试试下面的 perl one liner:

perl -lpe "s/<\/?script>//g" inputfile

【讨论】:

    【解决方案2】:

    在 perl 中:

    $string =~ s!<script[^>]*>|.*</\s*script>!!g;
    

    【讨论】:

    • 这只会删除开始的 。无论如何,谢谢..我会理解这个表达并找出原因。谢谢
    • 如果脚本中的文本覆盖多行,您可能需要使用修饰符;见perldoc.perl.org/perlre.html#Modifiers
    • g - 修饰符会有所帮助
    【解决方案3】:

    在 perl 中,您可以进行测试以检查它是否与您的标签匹配,然后进行替换。

    #!/usr/bin/perl
    
    use warnings; 
    use strict;
    
    my $string = '<script>This String may contain other JS tags in between </script>';
    
    if ( $string =~ /^(<script>).*(<\/script>)$/ ) {
    $string =~ s/$1|$2//g;
    }
    print $string, "\n";
    

    这将打印:

    This String may contain other JS tags in between
    

    【讨论】:

    • $string =~ s/^(
    【解决方案4】:

    您可以尝试以下代码来删除开始和结束脚本标签。

    "<script>This String may contain other JS tags in between </script>".replace(/^<script>|<\/script>$/g, "");
    'This String may contain other JS tags in between '
    

    或

    "foo <script>This String may contain other JS tags in between </script> foo".replace(/^((?:(?!<script>).)*)<script>(.*?)<\/script>((?:(?!<script>).)*)$/g, "$1$2$3");
    'foo This String may contain other JS tags in between  foo'
    

    通过 perl,

    $ echo 'foo <script>This String may contain other JS tags in between </script> foo' | perl -pe 's/^((?:(?!<script>).)*)<script>(.*?)<\/script>((?:(?!<script>).)*)$/\1\2\3/g'
    foo This String may contain other JS tags in between  foo
    

    【讨论】:

    • "如何在 Perl 中做到这一点?" © 阿尔比
    猜你喜欢
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多