我有以下字符串:
string str ="dasdsa|cxzc|12|#dsad#|czxc";
我需要一个返回的函数:#dsad#
考虑到#dsad#
是动态创建的,因此它可能会有所不同,而且它的长度也会有所不同
如何使用正则表达式(在两个主题标签之间搜索字符串)或其他方法(如果可用)?
答案 0 :(得分:2)
假设您想匹配#字符,可以使用以下正则表达式:
#[a-z]+#
如果你想要你的字符串总是1 | 2 | 3 |#4#| 5的形式你可以使用String.Split(' |')方法,只需取第四个元素结果。
答案 1 :(得分:2)
假设#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("#"))
答案 2 :(得分:2)
如果您的字符串是以竖线分隔的字符串,则可以使用|
进行拆分,并获取以#
开头和结尾的值。
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);
如果您只需要一个值,请使用.FirstOrDefault()
:
var result = str.Split('|')
.Where(p => p.StartsWith("#") && p.EndsWith("#"))
.FirstOrDefault();
答案 3 :(得分:2)
根据问题中给出的输入,你需要搜索下面两个主题标签之间的字符串,将是正则表达式,
^.*#(.*)#.*$
如果2个主题标签之间的数据为空,那么正则表达式仍然不会失败。这将是空值。
答案 4 :(得分:1)
这似乎是带有五个数据部分的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
中显示的数据: