【问题标题】:Regular expression for a string that does not start with a /*不以 /* 开头的字符串的正则表达式
【发布时间】:2014-10-28 10:05:15
【问题描述】:

我使用 EditPad Pro 文本编辑器。 我需要将字符串读入代码,但我需要忽略以标签“/*”或tab + /*开头的字符串,例如:

/**
 * Light up the dungeon using "claravoyance"
 *
 * memorizes all floor grids too.
**/ 
/** This function returns TRUE if a "line of sight" **/
#include "cave.h"
 (tab here) /* Vertical "knights" */

if (g->multiple_objects) {
  /* Get the "pile" feature instead */
  k_ptr = &k_info[0];
}

put_str("Text inside", hgt - 1, (wid - COL_MAP) / 2);

/* More code*** */

我喜欢返回:

"Text inside"

我试过这个(阅读Regular expression for a string that does not start with a sequence),但对我不起作用:

^(?! \*/\t).+".*"

有什么帮助吗?

编辑:我用过:

^(?!#| |(\t*/)|(/)).+".*"

然后它返回:

put_str("Text inside"

我即将找到解决方案。

【问题讨论】:

    标签: regex editpad


    【解决方案1】:

    EditPad 显然支持 pro 版本 6lite 版本 7 中的variable-length lookbehind,因为它是flavor is indicated as "JGsoft": Just Great Software regular expression engine

    知道这一点并且不使用capture groups,您可以组合两个可变长度lookbehinds

    (?<!^[ \t]*/?[*#][^"\n]*")(?<=^[^"\n]*")[^"]+
    
    • (?&lt;!^[ \t]*/?[*#][^"\n]*") 用于避免引用部分前面有 [ \t]*/?[*#] 任何 cmets 的负面回溯,前面可以有任意数量的空格/制表符。将/ 设为可选,因为多行注释也可以以* 开头。
    • (?&lt;=^[^"\n]*") 肯定的后向保证,[^"\n]characters, that are no quotes or newlines 后面跟一个引号。
    • [^"]+ 应该总是平衡引用,现在应该很方便,在第一个 double-quote 之后匹配 non-quotes (在后面的里面)
    • 如果任何一行中可能出现单个"(不平衡),请将结尾:[^"]+ 更改为[^"\n]+(?=")

    这个问题可能有不同的解决方案。希望对你有帮助:)

    【讨论】:

    • 几乎!我忘了包含代码:#include "cave.h",而你的解决方案显示 "cave.h",可以改进正则表达式吗?
    • @HernaldoGonzalez 那么以# 开头的行(前面有可选空格)也不应该考虑在内吗?查看更新的答案。
    • @HernaldoGonzalez 感谢您的夸奖,同时也学到了新知识,同时考虑到您的正则表达式问题 :) 太好了,现在解决了!
    【解决方案2】:

    这是一种方法:^(?!\t*/\*).*?"(.+?)"

    细分:

    ^(?!\t*/\*)  This is a negative lookahead anchored to the beginning of the line, 
                 to ensure that there is no `/*` at the beginning (with or 
                 without tabs)
    
    .*?"         Next is any amount of characters, up to a double-quote. It's lazy 
                 so it stops at the first quote
    
    
    (.+?)"       This is the capture group for everything between the quotes, again
                 lazy so it doesn't slurp other quotes
    

    【讨论】:

    • 非常接近,但返回给我:put_str("Text inside"
    • 您只想查看捕获组(组 1),而不是整个匹配。
    【解决方案3】:

    你可以使用这个正则表达式:

    /\*.*\*/(*SKIP)(*FAIL)|".*?"
    

    Working demo

    编辑:如果你使用 EditPad,那么你可以使用这个正则表达式:

    "[\w\s]+"(?!.*\*/)
    

    【讨论】:

    • 我使用 EditPad Pro 文本编辑器,即 /*.**/(SKIP)(*FAIL)|".?"失败。
    • @HernaldoGonzalez 你能用这个例子检查一下regex101.com/r/aC4vO4/3 吗?
    • regex101.com 中工作正常,但在 EditPad 中返回更多字符,很奇怪。我将等待两天进行评估。
    • @HernaldoGonzalez 我会尝试找出另一个答案。顺便说一句,因为它适用于 regex101 也许你可以使用它而不是 EditPad
    • @HernaldoGonzalez 我想你正在寻找这个regex101.com/r/aC4vO4/4
    猜你喜欢
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2014-08-15
    • 2015-05-14
    • 2011-01-08
    相关资源
    最近更新 更多