繁体   English   中英

从C#中的字符串中获取所有类似@ * @的单词的最佳方法

[英]Best way to get all words like @*@ from a string in C#

我有一个类似“ @ 1234 @ == val1 && @ 2312 @!= val2”的字符串。 我想获取使用'@'嵌入的1234和2312,分隔成一个数组。 该字符串可以包含多个使用'@'嵌入的项目。

update :将仅包含'@'之间的整数值。

update2 :可能出现的有效输入字符串是“ @some int value @ == val1”或类似的字符串,用“ &&”或“ ||”分隔 示例输入字符串:

              "@234@ == val1",
              "@3456@ == 345 && @34563@ != 'Y'",
              "@1234@ != val1 || @1234@ != val2 || @1234@ != val3"      

实现此目标的最佳方法是什么?

试试:(包括签名值)

//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);
}

使用LINQ的另一种方法:

 var list = input.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
 var result = Enumerable.Range(0, list.Length / 2)
                        .Select(i => list.ElementAt(i*2));

如果您的输入像:

 "@12@@34@ == val1 && @2312@ != val2"

您可以在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM