简体   繁体   English

如何在 c# 中的两个字符串之间查找字符串

[英]How to find strings between two strings in c#

I'm getting a string with some patterns, like:我得到一个带有一些模式的字符串,比如:

A 11 A 222222 B 333 A 44444 B 55 A 66666 B

How to get all the strings between A and B in the smallest area?如何在最小区域中获取 A 和 B 之间的所有字符串?

For example, "A 11 A 222222 B" result in " 222222 "例如,“A 11 A 222222 B”导致“222222”

And the first example should result in:第一个示例应导致:

222222 
333 
44444 
55 
66666

We can try searching for all regex matches in your input string which are situated between A and B , or vice-versa.我们可以尝试在您的输入字符串中搜索位于AB之间的所有正则表达式匹配,反之亦然。 Here is a regex pattern which uses lookarounds to do this:这是一个使用环视来执行此操作的正则表达式模式:

(?<=\bA )\d+(?= B\b)|(?<=\bB )\d+(?= A\b)

Sample script:示例脚本:

string input = "A 11 A 222222 B 333 A 44444 B 55 A 66666 B";
var vals = Regex.Matches(input, @"(?<=\bA )\d+(?= B\b)|(?<=\bB )\d+(?= A\b)")
    .Cast<Match>()
    .Select(m => m.Value)
    .ToArray();
foreach (string val in vals)
{
    Console.WriteLine(val);
}

This prints:这打印:

222222
333
44444
55
66666

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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