1

假设我有一些原文:

这是一些包含我感兴趣的子字符串的文本。

我需要文本来匹配它的一部分,比如:“ has a substring”。

但是,原始文本和匹配字符串可能存在空格差异。例如,匹配文本可能是:

有个
子串

或者

有一个子串

和/或原文可能是:

这是一些
有的文字
我有兴趣嵌入其中的子字符串。

我需要我的程序输出的是:

这是一些文本,[匹配从这里开始]有一个我感兴趣的子字符串[匹配到这里]嵌入其中。

我还需要保留原始中的空白模式,只需向其中添加开始和结束标记。

关于使用 Perl 正则表达式来实现这一点的任何想法?我试过了,但最终变得非常混乱。

4

5 回答 5

5

自从我使用 perl 正则表达式以来已经有一段时间了,但是呢:

$match = s/(has\s+a\s+substring)/[$1]/ig

这将在单词之间捕获零个或多个空格和换行符。它将用括号包裹整个匹配,同时保持原始分隔。它不是自动的,但它确实有效。

你可以用它来玩游戏,比如拿一根绳子"has a substring",对它做一个变换,让它变得"has\s*a\s*substring"不那么痛苦。

编辑:合并了 ysth 的评论,即 \s 元字符与换行符匹配,并且 hobbs 更正了我的 \s 用法。

于 2009-09-15T03:50:54.980 回答
3

此模式将匹配您要查找的字符串:

(has\s+a\s+substring)

因此,当用户输入搜索字符串时,将搜索字符串中的任何空格替换为\s+您的模式。,只需将每个匹配项替换为匹配文本[match starts here]$1[match ends here]所在的位置。$1

于 2009-09-15T03:51:39.830 回答
2

在正则表达式中,您可以使用+来表示“一个或多个”。所以像这样

/has\s+a\s+substring/

匹配has后跟一个或多个空白字符,后跟a一个或多个空白字符,然后是substring.

将它与替换运算符放在一起,您可以说:

my $str = "here is some text that has     a  substring that I'm interested in embedded in it.";
$str =~ s/(has\s+a\s+substring)/\[match starts here]$1\[match ends here]/gs;

print $str;

输出是:

here is some text that [match starts here]has     a  substring[match ends here] that I'm interested in embedded in it.
于 2009-09-15T03:55:25.407 回答
0

许多人建议,使用\s+匹配空格。这是您自动执行此操作的方法:

my $original = "here is some text that has a substring that I'm interested in embedded in it.";
my $search = "has a\nsubstring";

my $re = $search;
$re =~ s/\s+/\\s+/g;

$original =~ s/\b$re\b/[match starts here]$&[match ends here]/g;

print $original;

输出:

here is some text that [match starts here]has a substring[match ends here] that I'm interested in embedded in it.

您可能想要转义字符串中的任何元字符。如果有人有兴趣,我可以添加它。

于 2009-09-15T10:38:00.680 回答
0

这是您如何做到这一点的一个示例。

#! /opt/perl/bin/perl
use strict;
use warnings;

my $submatch = "has a\nsubstring";

my $str = "
here is some
text that has
a substring that I'm interested in, embedded in it.
";

print substr_match($str, $submatch), "\n";

sub substr_match{
  my($string,$match) = @_;

  $match =~ s/\s+/\\s+/g;

  # This isn't safe the way it is now, you will need to sanitize $match
  $string =~ /\b$match\b/;
}

这目前可以检查$match变量中是否存在不安全字符。

于 2009-09-15T17:06:45.907 回答