[英]get specific string pattern
我有以下字符串:
string str ="dasdsa|cxzc|12|#dsad#|czxc";
我需要一个返回的函数: #dsad#
考虑到#dsad#
是动态创建的,因此它可能会有所不同,并且其长度也可能会有所不同
我如何使用正则表达式(搜索两个主题标签之间的字符串)或其他可用方法来做到这一点?
假设您要匹配#字符,可以使用以下正则表达式:
#[az]+#
如果希望您的字符串始终为1 | 2 | 3 |#4#| 5的形式,则可以使用String.Split('|')方法并仅使用结果的第四个元素。
假设#dasd#
在字符串中仅出现一次,请尝试以下操作:
String a = "asd|asd|#this#|asdasd";
string m = Regex.Match(a, @"#.+#").Value;
Console.WriteLine(m);
.+
搜索任何字符
如果您的字符串使用|
作为分隔符,您也可以分割字符串。
string [] array = a.Split('|');
// this would get a list off all values with `#`
List<string> found_all = array.Where(x => x.Contains("#")).ToList();
// this would get the first occurrence of that string. If not found it will return null
string found = array.FirstOrDefault(x => x.Contains("#"))
如果您的字符串是用竖线分隔的字符串,则可以使用|
分隔|
,并获取以#
开头和结尾的值。
var str ="dasdsa|cxzc|12|#dsad#|czxc";
var result = str.Split('|').Where(p => p.StartsWith("#") && p.EndsWith("#")).ToList();
foreach (var s in result)
Console.WriteLine(s);
请参阅在线C#演示 。
如果只需要一个值,请使用.FirstOrDefault()
:
var result = str.Split('|')
.Where(p => p.StartsWith("#") && p.EndsWith("#"))
.FirstOrDefault();
根据问题中给出的输入,您需要搜索下面两个标签之间的字符串将是正则表达式,
^.*#(.*)#.*$
如果两个标签之间的数据为空,则正则表达式仍不会失败。 它将为空值。
这似乎是带有五个数据部分的CSV分隔数据。
提取每个部分,然后使用正则表达式表示每个部分,将其投影到动态实体中。
string data = "dasdsa|cxzc|12|#dsad#|czxc";
string pattern = @"(?<Section1>[^|]+)\|(?<Section2>[^|]+)\|(?<Section3>[^|]+)\|(?<Section4>[^|]+)\|(?<Section5>[^|]+)";
var results =
Regex.Matches(data, pattern, RegexOptions.ExplicitCapture)
.OfType<Match>()
.Select(mt => new
{
One = mt.Groups["Section1"].Value,
Two = mt.Groups["Section2"].Value,
Three = mt.Groups["Section3"].Value,
Four = mt.Groups["Section4"].Value,
Five = mt.Groups["Section5"].Value,
})
.ToList();
Console.WriteLine(results[0].Four ); // #dsad#
一旦完成,从results
包含什么。 因为它只是多行捕获的列表,其中每行仅包含该行数据的一个实体。
从适当的属性中提取; 而我们的最终结果只有一行,但是我们可以如示例WriteLine
所示获得数据:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.