简体   繁体   English

正则表达式忽略大括号

[英]regex to ignore curly brackets

{unknown string}  
{unknown string  
unknown string}
unknown string

How do I come up with a regex that recognizes just the string (which is unknown, so I cannot do an explicit match to a specific string) in all four of the above cases? 在上述所有四种情况下,如何提出仅识别字符串的正则表达式(未知,因此我无法对特定字符串进行显式匹配)?

You haven't tried much, have you? 您没有尝试太多,对吗?

string result = Regex.Match(input, "hello").Value;

If you just want something between curly braces: 如果您只需要花括号之间的内容:

string result = Regex.Match(input, @"\{?(.*)\}?").Groups[1].Value;
\w+

It will match all "word"-characters 它将匹配所有“单词”字符

If you need to generalize it to something that's "between optional curly braces" you could use: 如果需要将其概括为“在花括号之间”,可以使用:

\{?(.+?)\}?

which means: 意思是:

  1. \\{? - an optional curly brace character. -可选的花括号字符。 It's escaped because { has a special meaning in regular expressions. 它之所以能逃脱是因为{在正则表达式中具有特殊含义。 ? quantifier means 0 or 1 times (thus optional) 量词表示01次(因此是可选的)
  2. (.+?) - means anything in non-greedy mode. (.+?) -表示非贪婪模式下的任何内容。 You need non-greedy here so that regex stops right before the following } (if any) 您需要在此处保持非贪婪状态,以便正则表达式在以下} (如果有的话)之前停止
  3. \\}? - the same as item #1 -与项目#1相同

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

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