正则表达式查找以相同数字开头的所有行,该行在该区域中具有特定字符串

时间:2016-07-19 08:33:09

标签: regex

我想找到所有“单词到找到”的行,并且不仅仅给出了这一行作为结果,而是接近该结果的所有行在行开头具有相同的数字。

因此,在下面的示例文本中,此正则表达式应该找到所有以777700和999900开头的行。

class A(){
    public B AnotherType { get; set; }
}

class B(){
    public string ShowMe { get; set; }
}

2 个答案:

答案 0 :(得分:2)

噢,这比起初我想的要复杂。这是我的解决方案:

^(\d+)\b(?=(?:(?!^(?!\1\b)).)*word-to-find)(?:(?!^(?!\1\b)).)*

使用gms修饰符表示您正在使用的正则表达式(全局匹配,点匹配全部,^匹配行首)。在Sublime(我不知道)中,您应该在正则表达式的最开头添加(?sm)以使其工作。

请再试一次on regex101.com

<强>解释

^               # Start of line
(\d+)           # Match and capture a number (group 1)
\b              # Make sure we match the entire number
(?=             # Now assert that the following can be matched from here on out:
 (?:            # Start of non-capturing group:
  (?!           # Allow a match only if it's impossible to match...
   ^(?!\1\b)    # ...the start of a line followed by a different number than \1
  )             # End of negative lookahead
  .             # Then match any character
 )*             # any number of times
 word-to-find   # and our search string.
)               # End of positive lookahead
(?:             # Now that we know our search string is there, let's do the actual match:
 (?!^(?!\1)\b)  # which extends until a line follows that starts with a different number
 .              # Match any character
)*              # any number of times

答案 1 :(得分:0)

在这种情况下,我更喜欢:

  • 添加显式记录分隔符 $(document).on("beforeSubmit", "#projectsId", function (e) { e.stopImmediatePropagation(); // submit form $.ajax({ url : $("#projectsId").attr('action'), type : 'post', data : $("#projectsId").serialize(), success: function(response) { if(response.status=="true") { $.pjax.reload({container:"#projectsGrid"}); $('#modal').modal("hide"); } else { $('#projectsId').yiiActiveForm('updateMessages', response.errors , true); } } }); return false; // Cancel form submitting. }); §替换^(\d+).*(\n\1.*)*
  • 进行我需要的处理(例如:find §$0
  • 删除分隔符

(未经测试:空格,字边界可能需要一些额外的工作)