Regex -用于从字符串中提取数据的各种正则表达式
本文关键字:数据 正则表达式 提取 用于 字符串 Regex | 更新日期: 2023-09-27 18:08:12
我有以下代码
string s = "add(2,3);";
var matchess = Regex.Matches(s, @"'('s*(?<num>'d+)'s*(','s*(?<num>'d+)'s*)*')");
var results = matchess.Cast<Match>()
.SelectMany(m => m.Groups["num"].Captures.Cast<Capture>())
.Select(c => c.Value).ToArray();
上面的代码检测到两个以上的functionname(number,number)输入,并将结果存储在一个数组列表中,以供访问。
是否有办法改变方程,使它也接受以下内容并相应地打印结果?
示例1 string s = "add(2.2,3.3);";
结果1 results[0] = 2.2
results[1] = 3.3
示例2 string s = "add(2.4,3.5,6.7);";
2结果 results[0] = 2.4
results[1] = 3.5
results[2] = 6.7
示例3
string s = "test("this is a test","just an example");";
结果3
results[0] = "this is a test"
results[1] = "just an example"
示例4
string s = "test("this is a test","just an example","testing");";
结果4
results[0] = "this is a test"
results[1] = "just an example"
results[2] = "testing"
基本上我需要的是采取超过2个输入的functionname(十进制,十进制)&函数名(string,string)并将结果存储在数组列表中以访问它们。
请建议。由于
试试这个:
string s = "aa(1.2,3.5)";
//Or
string s = "aa(sad,asd)";
var info = Regex.Split(
Regex.Matches(s, @"'(.*?')")
.Cast<Match>().First().ToString()
.Replace("(", string.Empty).
Replace(")", string.Empty), @"['s,]+");
工作原理:
首先我得到字符串在()
区域:
Regex.Matches(s, @"'(.*?')");
获取第一个匹配
.Cast<Match>().First().ToString()
去除(
和)
.Replace("(", string.Empty).Replace(")", string.Empty)
在,
形式结果之间分割文本或数字
Regex.Split(result, @"['s,]+");