分组regex帮助
本文关键字:帮助 regex 分组 | 更新日期: 2023-09-27 18:00:21
我有这个正则表达式来定义标识符:
['w|@|#|_]['w|'.|'$|@|#|_]*
我需要允许使用[group]或"group"分组的标识符组,并且为了允许"s"在"group"内,你需要写"(两个),对于[group],你需要做]]对一个]。
该组可能包含标识符、空格和以下任何字符中允许的任何内容:波浪号(~)连字符(-)感叹号(!)左大括号({)百分比(%)右大括号(})插入符号(^)撇号(')安培数(&)周期(.)左括号(()反斜杠()右括号())重音重音符(`)
示例:
"asda$@.asd ' a12876 ]] "" " => asda$@.asd ' a12876 ]] "
[asda$@.asd ' a12876 ]] "" ] => asda$@.asd ' a12876 ] ""
在[character classes]
中不需要任何|
,因为它会导致任何字符匹配。(例如,我假设您不希望标识符以|
开头。
string mystring = "[asda$@.asd ' a12876 ]] '"'" ]";
Console.WriteLine(mystring);
MatchCollection matches =
Regex.Matches(mystring,
@"['w@#](?:['w'.'$@#])*|'[['w@#](?:'['[|']']|[""'w's'.'$@#'])*']|""['w@#](?:'""'""|[''s'['w'.'$@#']])*""",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match match in matches)
{
string id = match.Value;
// The first character of the match tells us which escape sequence to use
// for the replacement.
if (match.Value[0] == '[')
id = id.Substring (1, id.Length - 2).Replace ("[[", "[").Replace ("]]", "]");
else if (match.Value[0] == '"')
id = id.Substring (1, id.Length - 2).Replace ("'"'"", "'"");
Console.WriteLine (id);
}