C# 在严格文本中获取文本的特定部分
假设有一个如下所示的文本:C# 在严格文本中获取文本的特定部分,c#,.net,string,c#-4.0,C#,.net,String,C# 4.0,假设有一个如下所示的文本: string str=@“stackoverflow(stack:stackoverflow)overstackflow(over:stackoverflow)” 我想要大胆的领域。 我想我必须在文本中找到“(”和“:”,并得到它们之间的文本,不是吗 有什么建议吗?看看这篇文章,你可以找到答案 您只需要对该正则表达式做一些小的更改。我会选择以下内容: string strRegex = @"\((.+?)\:"; RegexOptions myRegexOption
string str=@“stackoverflow(
stack:stackoverflow)overstackflow(
over:stackoverflow)”代码>
我想要大胆的领域。
我想我必须在文本中找到“(”和“:”,并得到它们之间的文本,不是吗
有什么建议吗?看看这篇文章,你可以找到答案
您只需要对该正则表达式做一些小的更改。我会选择以下内容:
string strRegex = @"\((.+?)\:";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"stackoverflow(stack:stackoverflow)overstackflow(over:stackoverflow)";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
Regex matcher = new Regex(@"([^():}]+)\(([^():}]*):([^():}]*)\)");
MatchCollection matches = matcher.Matches(str);
这将在您的输入中查找所有类似于group1(group2:group3)
(如果其中任何一个组包含(
,)
或:
的内容,则整个内容将被忽略,因为它无法确定应该在哪里。)
然后,您可以获得匹配的值,例如
foreach(Match m in matches)
{
Console.WriteLine("First: {0}, Second: {1}, Third{2}",
m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value);
}
因此,如果您只需要(
和:
之间的位,您可以使用
foreach(Match m in matches)
{
Console.WriteLine(m.Groups[2].Value);
}
可能使用纯string
方法:
IList<String> foundStrings = new List<String>();
int currentIndex = 0;
int index = str.IndexOf("(", currentIndex);
while(index != -1)
{
int start = index + "(".Length;
int colonIndex = str.IndexOf(":", start);
if (colonIndex != -1)
{
string nextFound = str.Substring(start, colonIndex - start);
foundStrings.Add(nextFound);
}
currentIndex = start;
index = str.IndexOf("(", currentIndex);
}
IList foundStrings=new List();
int currentIndex=0;
int index=str.IndexOf(“(”,currentIndex);
while(索引!=-1)
{
int start=index+“(”.Length;
int colindex=str.IndexOf(“:”,start);
如果(克隆索引!=-1)
{
字符串nextFound=str.Substring(start,colonIndex-start);
foundStrings.Add(nextFound);
}
当前索引=开始;
index=str.IndexOf(“(”,currentIndex);
}
结果是stack
,但您可以在foreach
循环中使用它来迭代字符串
你是指你的字符串中间的底线吗?在他们不编码你的标签的时候。假设有一个文本,我想得到文本BEWEN。(和:运算符。我该怎么做?你想得到是/否的答案吗?为什么不自己试试呢?使用子字符串和IndexOf
将对你有所帮助。首先,我想知道这是一个好方法吗?我可以试试我想知道任何理想的方法吗?检查myMatch没有意义。成功但你可能想展示如何获得值代码>输出。@Tim你只在你回答时使用,还是同时使用Visual Studio?ideone快吗?@SonerGönül:仅用于演示目的。它不快,它使用单声道,有很多限制。@TimSchmelter解决其他问题,Visual Studio或Linqpad?@SonerGönül我想他只用于演示
public static void Main(string[] args)
{
string str = @"stackoverflow(stack:stackoverflow)overstackflow(over:stackoverflow)";
Console.WriteLine(ExtractString(str));
}
static string ExtractString(string s)
{
var start = "(";
int startIndex = s.IndexOf(start) + start.Length;
int endIndex = s.IndexOf(":", startIndex);
return s.Substring(startIndex, endIndex - startIndex);
}