所以我试图在字符串中查找字符串,现在我已经构建了这个字符串,
string str4;
var str5 = " type: '");
foreach (string str6 in response.Split(new char[] { '\n' }))
{
if (str6.StartsWith(str5))
{
str4 = str6.Replace(str5, "").Replace(" ", "").Replace("',", "");
break;
}
}
它按预期工作并且将从中获取文本
type: '
这个例子是
type: ' EXAMPLE ',
循环后的输出
EXAMPLE
现在的问题是,“type:”开头的空格有时会有所不同,因此有时它可能等于我提供的空格,有时则可能不等于。
我试图使用正则表达式,这样我就可以做一些事情,例如,
string str5 = "Regex(*)type: '"
当然,这在用法上是完全不正确的,但我的示例显示了 * 的使用,它等于任何可能性,因此无论空格数量如何,我仍然能够从中提取内部文本类型。
最佳答案
在这里,我们只需在所需输出之前和之后添加可选空格,例如 Example
,我们可以从此表达式开始,例如:
type:(\s+)?'(\s+)?(.+?)(\s+)?',
Demo
或者:
type:(\s+)?'(\s+)?(.+?)(\s+)?'
如果我们可能有 '
类型,我们会将表达式扩展为:
type:(\s+)?['"](\s+)?(.+?)(\s+)?['"]
测试
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"type:(\s+)?'(\s+)?(.+?)(\s+)?',";
string input = @"type:' EXAMPLE ',
type: ' EXAMPLE ',
type: ' EXAMPLE ',
type: ' Any other EXAMPLE we might have ',";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
正则表达式电路
jex.im可视化正则表达式:
关于C# 字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528633/