C# 正则表达式,用于在带有“的txt文件中查找GUID字符串”;id=”号;附属于它
下面的代码运行良好,目标是在XML文件中查找GUID字符串。例如,它将查找字符串C# 正则表达式,用于在带有“的txt文件中查找GUID字符串”;id=”号;附属于它,c#,regex,C#,Regex,下面的代码运行良好,目标是在XML文件中查找GUID字符串。例如,它将查找字符串A03DD607-90BF-4077-ADA8-C6E76F9D4759,但现在我尝试将正则表达式更改为仅查找: id=“A03DD607-90BF-4077-ADA8-C6E76F9D4759” 而不是 A03DD607-90BF-4077-ADA8-C6E76F9D4759 这是我的密码: //obtain all GUIDs in the XML file using (StreamReader
A03DD607-90BF-4077-ADA8-C6E76F9D4759
,但现在我尝试将正则表达式更改为仅查找:
id=“A03DD607-90BF-4077-ADA8-C6E76F9D4759”
而不是
A03DD607-90BF-4077-ADA8-C6E76F9D4759
这是我的密码:
//obtain all GUIDs in the XML file
using (StreamReader sr = File.OpenText(xmlFile))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
MatchCollection guids = Regex.Matches(s, @"(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}");
for (int i = 0; i < guids.Count; i++)
{
Console.WriteLine(guids[i].Value);
guidList.Add(guids[i].Value.ToUpper());
}
}
}
//获取XML文件中的所有GUID
使用(StreamReader sr=File.OpenText(xmlFile))
{
string s=string.Empty;
而((s=sr.ReadLine())!=null)
{
MatchCollection guids=Regex.Matches(s,@“({0,1}[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}[0,1}”);
for(int i=0;i
您可以使用以下代码替换相应的代码行:
MatchCollection guids = Regex.Matches(s, @"id=""\{?[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}}?""");
在C#(参见本链接第2点)中,看起来像@“…”
,文字引号必须加倍
{0,1}
限制量词可以安全地更改为?
(出现1次或0次)
字符类外部的-
字符(不在[…]
构造内部)不必转义
请参阅。我会将文本
Guid
的识别推迟到Guid.TryParse()
。这将正则表达式简化为如下内容:
private const RegexOptions rxOptions = RegexOptions.IgnoreCase
| RegexOptions.ExplicitCapture
| RegexOptions.CultureInvariant
;
private static readonly Regex rxGuidId = new Regex( @"id=""(?<guid>[^""]+)""", rxOptions );
private static Guid[] ExtractGuidsFromText( string s )
{
return rxGuidId
.Matches( s ?? "" )
.Cast<Match>()
.Where( m => m.Success )
.Select( m => {
Guid instance;
bool validGuid = Guid.TryParse( m.Groups["guid"].Value , out instance ) ;
return validGuid ? (Guid?)instance : (Guid?)null ;
})
.Where( g => g.HasValue )
.Select( g => g.Value )
.ToArray()
;
}
//获取XML文件中的所有guid
为什么不使用.NET内置的XML解析器而不是Regex?使用查询只需*[@id]
谢谢您的建议。我特别喜欢它们,因为您正在解析Guid,但TryParse对我不起作用,因为我们还不能使用.Net4:(@LeresAldtai)我对答案做了一些改进。
private static IEnumerable<Guid> ExtractGuidsFromText( string s )
{
for ( Match m = rxGuidId.Match( s ?? "" ) ; m.Success ; m = m.NextMatch() )
{
Guid instance;
bool parsed = Guid.TryParse( m.Groups["guid"].Value , out instance ) ;
if ( parsed ) yield return instance;
}
}
static IEnumerable<string> ReadGuidsFromXml( TextReader input )
{
using ( XmlReader reader = XmlReader.Create( input ) )
{
while ( reader.Read() )
{
if ( reader.NodeType != XmlNodeType.Element ) continue ;
for ( bool hasAttributes = reader.MoveToFirstAttribute() ; hasAttributes ; hasAttributes = reader.MoveToNextAttribute() )
{
if ( !string.Equals( reader.Name , "id" , StringComparison.OrdinalIgnoreCase ) ) continue ;
Guid guid;
if ( Guid.TryParse( reader.Value , out guid ) )
{
yield return guid;
}
}
}
}
}