【问题标题】:c regexp and negative look aheadc 正则表达式和负向前看
【发布时间】:2012-05-29 07:33:10
【问题描述】:

我有一个这样的字符串:

"result is abcdefg hij!klm </td"(或其他所有内容,而不是 abcd...)

我制作的正则表达式是:
"result is ([^<]+) </td"

这很好用,因为找到了结果。但是当字符串是:
"result is not found </td"
...如何避免提取“未找到”字样?

我知道有负面的前瞻表达式,但这些在 C99 的 regex.h 中不起作用。

  • "(?!not found)" -> 错误的正则表达式
  • "([^n][^o][^t][^ ][^f]..)" -> 不匹配“现在”,例如
  • "(([^<]+)&(!not found))" -> 不好 正则表达式

(没有'&'操作符,我觉得解决办法可以是:a&&b == !a||!b

--编辑--
在这里,您是计算正则表达式的代码部分。

pmatch=malloc(nmatch*sizeof(regmatch_t));  

printf("regex: %s\n",patrn);

if (regcomp(&rgT,patrn,REG_EXTENDED | REG_NEWLINE) != 0)
{
    snprintf(globals.err_buff,MAX_BUFF,"bad regex: \"%s\"",patrn);
    w_report_error(globals.err_buff,__FILE__,__LINE__,__func__,0,0,error);
    return EXIT_FAILURE;
}

-- 编辑--
也许我找到了解决方案:
如果将数字 > 0 作为参数传递给我自己的正则表达式函数,则返回第 N 个反向引用,所以...
注意:./regex 只是一个将 argv[...] 重定向到我自己库的 w_regexp 的 C 程序。

$ ./regex "result is crack </td" 'result is (not found) </td|result is ([^<]+) </td' 3
regex: result is (not found) </td|result is ([^<]+) </td
"crack"
""
"result is crack </td"
$ ./regex "result is not found </td" 'result is (not found) </td|result is ([^<]+) </td' 3
regex: result is (not found) </td|result is ([^<]+) </td
""
"not found"
"result is not found </td"  

所以,我认为在我的结构中添加一个数字,这意味着用于提取数据的反向引用的索引可能是一个解决方案,但我仍然会等待另一天或 2 天的更好方法。
提前致谢。

--编辑--(太多次:))
有用! 我已经把我想避免追随者的字符串放在'|'以及正确字符串的模式。
这是正则表达式:
"result is not found &lt;/td|result is ([^&lt;]+) &lt;/td"
再次感谢。

【问题讨论】:

    标签: c regex


    【解决方案1】:

    也许像"result is (?:not found)?([^&lt;]+)&lt;/td"

    【讨论】:

      【解决方案2】:

      Aztaroth 的作品也是 result is ((?!not found)[^&lt;]+) &lt;/td - 不同之处在于他注册了一个空匹配,我没有注册一个匹配。

      经过测试

      result is abcdefg hij!klm </td
      result is not found </td
      result is not this </td
      result is note this </td
      result is ote this </td
      

      编辑: 很遗憾,好吧 - 这很懒惰而且有点糟糕,但是使用正则表达式进行两次传递怎么样?第一个检查“未找到”result is (not found) &lt;/td 上的匹配项。然后,使用您原来的正则表达式进行不匹配,去掉结果。

      【讨论】:

      • 是的,我有这样的想法,但我在一个使用了数十次的结构上使用它(动态列表),因此,您的解决方案将在每个结构上添加一个模式,并且需要加倍解析每个结构上的数十个字符串,所有这些都只针对一个特定的事件......我希望有更好的解决方案......
      猜你喜欢
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      相关资源
      最近更新 更多