加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – 有没有办法,使用正则表达式,匹配引号之外的文本模

发布时间:2020-12-14 05:36:07 所属栏目:百科 来源:网络整理
导读:正如标题中所述,是否有一种方法,使用正则表达式来匹配出现在引号之外的文本的文本模式.理想情况下,给出以下示例,我希望能够匹配引号之外的逗号,但不能匹配引号中的逗号. This is some text,followed by “text,in quotes!” 要么 This is some text,in quote
正如标题中所述,是否有一种方法,使用正则表达式来匹配出现在引号之外的文本的文本模式.理想情况下,给出以下示例,我希望能够匹配引号之外的逗号,但不能匹配引号中的逗号.

This is some text,followed by “text,in quotes!”

要么

This is some text,in quotes” with more “text,in quotes!”

另外,如果表达式遵循嵌套引号会很好,如下例所示.但是,如果这对于正则表达式在技术上是不可行的,那么很容易知道是否是这种情况.

The programmer looked up from his desk,“This can’t be good,” he exclaimed,“the system is saying ‘File not found!'”

我找到了一些用于匹配引号中的内容的表达式,但对引号之外的内容没什么用.

解决方法

这可以通过现代正则表达式完成,因为存在大量的正则表达式引擎,但让我成为发布“不要使用正则表达式”答案的人.

这不是正则表达式的工作.这是一个完整的解析器的工作.作为一些你不能用(经典)正则表达式做的事情的例子,考虑一下:

()(())(()())

没有(经典)正则表达式可以确定这些括号是否匹配正确,但这样做没有正则表达式是微不足道的:

/* C code */

char string[] = "()(())(()())";
int parens = 0;
for(char *tmp = string; tmp; tmp++)
{
  if(*tmp == '(') parens++;
  if(*tmp == ')') parens--;
}
if(parens > 0)
{
  printf("%s too many open parenthesis.n",parens);
}
else if(parens < 0)
{
  printf("%s too many closing parenthesis.n",-parens);
}
else
{
  printf("Parenthesis match!n");
}

# Perl code

my $string = "()(())(()())";
my $parens = 0;
for(split(//,$string)) {
  $parens++ if $_ eq "(";
  $parens-- if $_ eq ")";
}
die "Too many open parenthesis.n" if $parens > 0;
die "Too many closing parenthesis.n" if $parens < 0;
print "Parenthesis match!";

看一下编写一些非正则表达式代码来完成这项工作是多么简单?

编辑:好的,从看到探险世界回来. :)试试这个(用Perl编写,评论是为了帮助你理解我在做什么,如果你不知道Perl):

# split $string into a list,split on the double quote character
my @temp = split(/"/,$string);

# iterate through a list of the number of elements in our list
for(0 .. $#temp) {

  # skip odd-numbered elements - only process $list[0],$list[2],etc.
  # the reason is that,if we split on "s,every other element is a string
  next if $_ & 1;

  if($temp[$_] =~ /regex/) {
    # do stuff
  }

}

另一种方法:

my $bool = 0;
my $str;
my $match;

# loop through the characters of a string
for(split(//,$string)) {

  if($_ eq '"') {
    $bool = !$bool;
    if($bool) {

      # regex time!
      $match += $str =~ /regex/;

      $str = "";
    }
  }

  if(!$bool) {

    # add the current character to our test string
    $str .= $_;
  }
}

# get trailing string match
$match += $str =~ /regex/;

(我给出两个,因为在另一种语言中,一个解决方案可能比另一个更容易实现,而不仅仅是因为有多种方法可以做到这一点.)

当然,随着你的问题越来越复杂,构建一个完整的解析器会产生某些好处,但那是一个不同的马.现在,这就足够了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读