[英]Best way to get all words like @*@ from a string in C#
I have a string like "@1234@ == val1 && @2312@ != val2". 我有一个类似“ @ 1234 @ == val1 && @ 2312 @!= val2”的字符串。 I want to get 1234 and 2312 which are embedded using '@' separated into an array. 我想获取使用'@'嵌入的1234和2312,分隔成一个数组。 The string can contain more than one items embedded using '@'. 该字符串可以包含多个使用'@'嵌入的项目。
update : will contain only integer values between '@'. update :将仅包含'@'之间的整数值。
update2 :valid input string which can occur are "@some int value@ == val1" or similar kind of string separated with '&&' or '||' update2 :可能出现的有效输入字符串是“ @some int value @ == val1”或类似的字符串,用“ &&”或“ ||”分隔 sample input strings: 示例输入字符串:
"@234@ == val1",
"@3456@ == 345 && @34563@ != 'Y'",
"@1234@ != val1 || @1234@ != val2 || @1234@ != val3"
what is the best way to achieve this? 实现此目标的最佳方法是什么?
try:(include signed value) 试试:(包括签名值)
//string patt = "@(?<value>.*?)@";
// string patt = "@(?<value>\\d*?)@"; // just number values (if there should be an integer use + instead of *)
//string patt = "@(?<value>[+|-]?\\d*?)@";
//string str = "@1234@ == val1 && @-2312@ != val2 && @+23@ != val3";
string patt = "@(?<value>[+|-]?\\d+?)@\\s[==|!=].*?(&&|\\|\\||$){1}";
string str = "@1234@ == val1 && @-2312@ != val2 && @+78@ != val3 || @45@ == 446";
Regex r = new Regex(patt);
string str = "@1234@ == val1 && @2312@ != val2";
MatchCollection mc = r.Matches(str);
List<string> lst = new List<string>();
foreach (Match item in mc)
{
string value = item.Groups["value"].Value;
lst.Add(value);
}
Another way using LINQ: 使用LINQ的另一种方法:
var list = input.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
var result = Enumerable.Range(0, list.Length / 2)
.Select(i => list.ElementAt(i*2));
In case your input like: 如果您的输入像:
"@12@@34@ == val1 && @2312@ != val2"
You can use this below Linq: 您可以在Linq下面使用它:
var list = input.Split(new[] { "==", "!=", "&&", "||" },
StringSplitOptions.RemoveEmptyEntries);
var result = Enumerable.Range(0, list.Length/2)
.Select(i => list.ElementAt(i*2).Trim())
.Select(s => s.Substring(1, s.Length - 2));
List<int> l=new List<int>();
string s="@1@ == val1 && @2@ != val2 || @3@ == val1";
Regex r=new Regex(@"(?<=@)[\d\s]+(?=@\s(==|!=).*?(&&|\|\||$){1})");
foreach(Match m in r.Matches(s))
{
l.AddRange(Regex.Split(m.Value,@"(?=\d)").Where(i=>i!="").Select(i=>int.Parse(i.Replace(" ",""))).ToList());
}
您应该使用的正则表达式:
(?<=@)[0-9]+(?=@)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.