110,549
社区成员
发帖
与我相关
我的任务
分享
pattern = @"(?msix)
^(\s*)if\b(?<key1>.*?):(?<value1>.*?) # 匹配 if 并记录前导空格
(^\1elif\b(?<key2>.*?):(?<value2>.*?))* # 匹配对应的 elif ,0个或多个
(^\1else\b(?<key3>.*?):(?<value3>.*?))? # 匹配对应的 else ,0个或1个
\Z # 匹配整个字符串末尾
";
static string pattern;
static Regex regex;
public void SetUp()
{
pattern = @"(?msix)
^(\s*)if\b(? <key1>.*?):(? <value1>.*?) # 匹配 if 并记录前导空格
(^\1elif\b(? <key2>.*?):(? <value2>.*?))* # 匹配对应的 elif ,0个或多个
(^\1else\b(? <key3>.*?):(? <value3>.*?))? # 匹配对应的 else ,0个或1个
\Z # 匹配整个字符串末尾
";
regex = new Regex(pattern, RegexOptions.Compiled);
}
// 可以考虑把正则表达式预编译为程序集,生成正则表达式的 Microsoft 中间语言 (MSIL) 代码;
// 以较长的启动时间为代价,得到更快的执行速度。
static string pattern = @"(?msix)
^(\s*)if\b(? <key1>.*?):(? <value1>.*?) # 匹配 if 并记录前导空格
(^\1elif\b(? <key2>.*?):(? <value2>.*?))* # 匹配对应的 elif ,0个或多个
(^\1else\b(? <key3>.*?):(? <value3>.*?))? # 匹配对应的 else ,0个或1个
\Z # 匹配整个字符串末尾
";
static Regex regex = new Regex(pattern, RegexOptions.Compiled);
private ArrayList GetLogicFormulaTopLevelIfThenList(string orginalFormulaScript)
{
ArrayList targetList = new ArrayList();
orginalFormulaScript = orginalFormulaScript.Trim().Replace("\r\n", "\n");
MatchCollection mc = regex.Matches(orginalFormulaScript);
foreach (Match m in mc)
{
// ...
}
}
"(?i)^(?=.*[A-Z].*[A-Z].*[A-Z]).{8,}$"
// 匹配到的 else 的 key3 及 value3
if (m.Groups["key3"].Success)
{
string key3 = m.Groups["key3" ].Value.Trim();
string value3 = m.Groups["value3"].Value;
Console.WriteLine("Key3 = [{0}]", key3 );
Console.WriteLine("Value3 = [{0}]", value3);
}
using System;
using System.Text.RegularExpressions;
class Program
{
static string str1 = @"
if 条件1 :
if 子条件1 : 子结果1
else 子条件2 : 子结果2
elif 条件2 :
计算2
elif 条件3 : 计算3
elif 条件4 : 计算4
else :
计算5
";
static void Main()
{
string s = RemoveEmptyLine(str1);
s = RemoveStartSapces(s);
Console.WriteLine("[{0}]", s);
}
// 去除空行
static string RemoveEmptyLine(string s)
{
return Regex.Replace(s, @"(?m)^\s*$", "").Replace("\n\n", "\n").TrimStart('\r', '\n');
// 如果也想去掉末尾的回车,只需所把 TrimStart 改成 Trim 即可。
}
// 去除开头的空白
static string RemoveStartSapces(string s)
{
string spaces = Regex.Match(s, @"^\s*").Value;
return Regex.Replace(s, "(?m)^" + spaces, "");
}
}
/* 输出:
[if 条件1 :
if 子条件1 : 子结果1
else 子条件2 : 子结果2
elif 条件2 :
计算2
elif 条件3 : 计算3
elif 条件4 : 计算4
else :
计算5
]
*/
using System;
using System.Text.RegularExpressions;
class Program
{
static string str1 = @"
if 条件1 :
if 子条件1 : 子结果1
else 子条件2 : 子结果2
elif 条件2 :
计算2
elif 条件3 : 计算3
elif 条件4 : 计算4
else :
计算5
";
static void Main()
{
string s = RemoveEmptyLine(str1);
s = RemoveStartSapces(s);
Console.WriteLine("[{0}]", s);
}
// 去除空行
static string RemoveEmptyLine(string s)
{
return Regex.Replace(s, @"(?m)^\s*$", "").Replace("\r\n\r\n", "\r\n").TrimStart('\r', '\n');
// 如果也想去掉末尾的回车,只需所把 TrimStart 改成 Trim 即可。
}
// 去除开头的空白
static string RemoveStartSapces(string s)
{
string spaces = Regex.Match(s, @"^\s*").Value;
return Regex.Replace(s, "(?m)^" + spaces, "");
}
}