简体   繁体   English

带有{^和^}的正则表达式

[英]Regex Pattern with {^ and ^}

I am trying to write a pattern that matches {^xyz^} as bellow, 我正在尝试写一个与{^xyz^}匹配的模式,如下所示,

@"\b\{\^\S*\^\}\b

But I am not getting success and wondering what is problem with my pattern. 但是我没有获得成功,并想知道我的模式有什么问题。

You can use: 您可以使用:

@"\{\^([^}]*)\^\}"

and extract captured group #1 for your string. 并为您的字符串提取捕获的组#1。

  • Use a captured group to get the substring you want to extract from a larger match. 使用捕获的组来获取要从较大匹配中提取的子字符串。
  • Word boundaries or \\b won't work here because { and } are non-word characters. 单词边界或\\b在这里不起作用,因为{}是非单词字符。
  • Use of negated character class [^}]* is more efficient and accurate than greedy \\S* . 否定字符类[^}]*比贪婪\\S*更加有效和准确。

I would simply use \\{\\^(\\S*?)\\^\\} . 我只会使用\\{\\^(\\S*?)\\^\\} This way you are capturing the contents between the carets and curly brackets. 这样,您就可以捕获插入符号和大括号之间的内容。 The ? ? is to make the * quantifier lazy, so it matches as little characters as possible (in order to prevent matching the beginning of one block until the end of another block in the same line). 是为了使*量词变得懒惰,因此它匹配的字符越少越好(以防止在同一行中匹配一个块的开始直到另一个块的结束)。

With those \\b you need a word-type character right before and after the curly braces for the regex to match. 对于那些\\b ,在正则表达式要匹配的花括号前后需要一个单词类型的字符。 Is that really a requirement? 这真的是要求吗? Or can there be a space? 还是可以有空间?

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

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