从Perl中的字符串中删除开始和结束标记

时间:2014-09-05 12:58:33

标签: javascript regex perl mason

我有一个这样的字符串:

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

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

我如何在Perl中执行此操作?

4 个答案:

答案 0 :(得分:2)

尝试以下perl one liner:

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

答案 1 :(得分:1)

在perl:

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

答案 2 :(得分:0)

您可以尝试使用以下代码删除开始和结束脚本标记。

"<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

答案 3 :(得分:0)

在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