[英]How can I return a list of words using regex, but define a word to also includes contents of a token?
因此,如果我的表達是:
var exp = "a b c (d e f (g h i) {foo}) {j k {l m}} n o p";
我的“令牌”分別是()和{},所以一旦您打了一個開頭(或{,它應該返回所有內容,直到找到結束令牌,即使存在嵌套令牌
此示例的匹配項應為:
a
b
c
(d e f (g h i) {foo})
{j k {l m}}
n
o
p
提交的重復問題似乎並沒有真正解決我匹配WORDS的問題。
var result = Regex.Matches(input, @"((\(.+\))|(\{.+\})|(\w+))")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList();
確實,平衡團體當然參與其中。 從使用RegEx平衡匹配括號起,我能夠創建以下內容,其中我以一種在編譯器中可以使用的格式進行了介紹,然后將其分解以解釋發生了什么
string pattern = @"\w|\(((?<BR>\()|(?<-BR>\))|[^()]*)+\)|\{((?<BR>\{)|(?<-BR>\})|[^{}]*)+\}";
string pattern = @"
\w| #Match any word OR
\(((?<BR>\()|(?<-BR>\))|[^()]*)+\)| #Match a () balanced group OR
\{((?<BR>\{)|(?<-BR>\})|[^{}]*)+\} #Match a {} balanced group
";
這將返回我期望的8個值。 平衡組示例中缺少的是一個簡單的\\ w匹配表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.