繁体   English   中英

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

[英]Removing starting and ending tags from a string in Perl

我有一个像这样的字符串:

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

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

我如何在Perl中做到这一点?

尝试以下perl一种衬垫:

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

在perl中:

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

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

"<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中,您可以进行测试以检查其是否与您的标签匹配,然后进行替换。

#!/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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM