简体   繁体   English

正则表达式匹配模式

[英]Regex match pattern

I am trying to count the amount of times I use \\n\\n\\n (3 linebreaks) after some text. 我正在尝试计算在某些文本后使用\\ n \\ n \\ n(3个换行符)的次数。 It counts almost as I like, the problem is when you spam newlines that will be counted which I don't want to. 这几乎是我想要的,问题是当您发送垃圾邮件时,这些垃圾邮件将被我不希望的计数。

Edit: Seems like the regex from regexr does not support .net so I have to come up with a pattern that works with .net. 编辑:好像从regexr的regex不支持.net,所以我不得不想出一个与.net一起使用的模式。

Example for the text that the regex will check on: 正则表达式将检查的文本示例:

Description for something 事物描述

text \\n \\n \\n // this will make DescriptionAmount++ 文字\\ n \\ n \\ n //这将使DescriptionAmount ++

Description for something 事物描述

text\\n \\n \\n // this will make DescriptionAmount++ text \\ n \\ n \\ n //这将使DescriptionAmount ++

\\n \\n \\n // this shouldn't add on DescriptionAmount \\ n \\ n \\ n //不应添加到DescriptionAmount

Here's the code I've done so far. 这是我到目前为止完成的代码。

int DescriptionAmount = Regex.Matches(somestring, "[^\w$](\r\n){2}[^\w$]").Count;

Try using a quantifier {x,y} to select how many tokens you want to match. 尝试使用量词{x,y}选择要匹配的令牌数。

The '*' will match the preceding character 0 or many times, meaning it will match any \\n after the 3rd token. “ *”将与前面的字符0或多次匹配,这意味着它将与第三个标记之后的任何\\ n匹配。

\\n{3} says \\n must be matched 3 times no more no less. \\ n {3}说\\ n必须匹配3次。

I find this tool http://regexr.com/ very useful for building and debugging regex statements. 我发现此工具http://regexr.com/对于构建和调试regex语句非常有用。

To ensure you capture the 3 linebreaks after some text would take something like: 为了确保您在某些文本之后捕获了3个换行符,需要执行以下操作:

\w+\s*\n{3}

Since this is .net, you either need to put an @ in front: 由于这是.net,因此您要么需要在前面加一个@:

@"\w+\s*\n{3}

or escape the slashes like: 或像这样逃脱斜线:

"\\w+\\s\n{3}

You mentioned that you are searching for three \\n , but your search has \\r\\n . 您提到要搜索三个\\n ,但是搜索到\\r\\n If you are looking for \\r\\n instead, just add \\r in front of the \\n and surround with () for (\\\\r\\\\n) or (\\r\\n) in the expressions above. 如果要查找\\r\\n ,只需在\\n前面添加\\r ,然后在上面的表达式中用()包围(\\\\r\\\\n)(\\r\\n)

One other thing, depending on the text in some string, you may want to apply the multiline option like: 另一件事,取决于某些字符串中的文本,您可能需要应用多行选项,例如:

Regex.Matches(somestring, "\\w\\s\n{3}", RegexOptions.Multiline)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM