[英]Regex to extract Variable Part
我有一個包含此的字符串:
@[User::RootPath]+"Dim_MyPackage10.dtsx"並且我需要使用正則表達式提取
[User::RootPath]
部分。
到目前為止,我有這個正則表達式:
[A-ZA-Z0-9] * \\。DTSX但我不知道如何進一步。
對於變量,為什么不使用not set [^ ]
來提取除 set 之外的所有內容,從而消耗所需的東西?
大括號中的^
表示查找不匹配的內容,例如,它查找不包含[ ]
或引號( "
)的所有內容。
然后,我們可以將實際匹配項放入命名捕獲組(?<{NameHere}> )
並進行相應提取
string pattern = @"(?:@\[)(?<Path>[^\]]+)(?:\]\+\"")(?<File>[^\""]+)(?:"")";
// Pattern is (?:@\[)(?<Path>[^\]]+)(?:\]\+\")(?<File>[^\"]+)(?:")
// w/o the "'s escapes for the C# parser
string text = @"@[User::RootPath]+""Dim_MyPackage10.dtsx""";
var result = Regex.Match(text, pattern);
Console.WriteLine ("Path: {0}{1}File: {2}",
result.Groups["Path"].Value,
Environment.NewLine,
result.Groups["File"].Value
);
/* Outputs
Path: User::RootPath
File: Dim_MyPackage10.dtsx
*/
(?: )
:)是匹配項,但不捕獲,因為我們將它們用作我們模式的事實上的錨,並且不將其放入匹配捕獲組。
您的正則表達式將匹配任意數量的字母數字字符,后跟.dtsx
。 在您的示例中,它將匹配MyPackage10.dtsx
。
如果要匹配Dim_MyPackage10.dtsx
,則需要在正則表達式中的允許字符列表中添加下划線: [a-zA-Z0-9]*.dtsx
如果要匹配[User::RootPath]
,則需要一個正則表達式,該正則表達式將停在最后一個/
(或\\
,取決於您在路徑中使用的斜杠類型):諸如此類: .*\\/
(或.*\\\\
)
從答案和評論中-到目前為止還沒有人“接受”這一事實-在我看來,這個問題/問題尚不完全清楚。 如果您正在尋找[User :: SomeVariable]模式,其中只有'SomeVariable'是變量,那么您可以嘗試:
\[User::\w+]
捕捉完整的表達。 此外,如果您希望檢測該模式,而僅需要“ SomeVariable”部分,則可以嘗試:
(?<=\[User::)\w+(?=])
使用環顧四周。
這是兄弟
using System;
using System.Text.RegularExpressions;
namespace myapp
{
class Class1
{
static void Main(string[] args)
{
String sourcestring = "source string to match with pattern";
Regex re = new Regex(@"\[\S+\]");
MatchCollection mc = re.Matches(sourcestring);
int mIdx=0;
foreach (Match m in mc)
{
for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
{
Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
}
mIdx++;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.