C#Regex如何捕获*|和|*之间的所有内容?
在C#中,我需要在短语*| variablename |*中捕获variablename 我有一个正则表达式:C#Regex如何捕获*|和|*之间的所有内容?,c#,regex,C#,Regex,在C#中,我需要在短语*| variablename |*中捕获variablename 我有一个正则表达式:RegEx RegEx=new RegEx(@“\*\\\\\\”(.*)\\\\*” 在线正则表达式测试程序返回“variablename”,但在C代码中,它返回*| variablename |*,或包含星号和条形字符的字符串。有人知道我为什么会经历这个返回值吗 多谢 using System; using System.Collections.Generic; using Syst
RegEx RegEx=new RegEx(@“\*\\\\\\”(.*)\\\\*”代码>
在线正则表达式测试程序返回“variablename”,但在C代码中,它返回*| variablename |*,或包含星号和条形字符的字符串。有人知道我为什么会经历这个返回值吗
多谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RegExTester
{
class Program
{
static void Main(string[] args)
{
String teststring = "This is a *|variablename|*";
Regex regex = new Regex(@"\*\|(.*)\|\*");
Match match = regex.Match(teststring);
Console.WriteLine(match.Value);
Console.Read();
}
}
}
//Outputs *|variablename|*, instead of variablename
match.Value
包含整个匹配项。这包括分隔符,因为您在正则表达式中指定了它们。当我用测试正则表达式并输入时,它会突出显示*| variablename*
您只想获取捕获组(括号中的内容),因此请使用match.Groups[1]
:
String teststring = "This is a *|variablename|*";
Regex regex = new Regex(@"\*\|(.*)\|\*");
Match match = regex.Match(teststring);
Console.WriteLine(match.Groups[1]);
谢谢你!如果我有String teststring=“这是一个*| variablename |*好的,我的*|朋友|*”;我是否需要使用MatchCollection方法,或者该组方法是否有效?您将需要MatchCollection,是的。这意味着MatchCollection matches=regex.matches(teststring)
。您仍将使用集合中每个匹配项的Group
属性—只需循环它即可。上面的正则表达式实际上捕获了第一个*|和最后一个*|之间的所有内容,而不是两个单独的项。处理这个问题的最佳方法是什么?有什么想法吗?谢谢您需要通过添加一个?
使捕获解除冻结,这样您的正则表达式就变成@“\*\\\\\\;(.*?\\\\*”
。