C# 正则表达式匹配枚举主体类型
我在文件中有这个枚举定义:
public enum IdentityState
{
[EnumMember]
New = 0,
[EnumMember]
Normal = 1,
[EnumMember]
Disabled = 2
}
{ some other data... }
并且只想匹配这个枚举的主体(在 {} 之间), 我想要的匹配结果是:
{
[EnumMember]
New = 0,
[EnumMember]
Normal = 1,
[EnumMember]
Disabled = 2
}
我制作这样的正则表达式模式:
public enum.*\w.*(?
但结果是这样的:
{
[EnumMember]
New = 0,
[EnumMember]
Normal = 1,
[EnumMember]
Disabled = 2
}
{ some other data... }
这不是我所期望的,因为它还包括我不想要的下一个 { some other data }
字符串。我不知道如何让模式在第一个 }
之后停止。
I have this enum defitiion in file:
public enum IdentityState
{
[EnumMember]
New = 0,
[EnumMember]
Normal = 1,
[EnumMember]
Disabled = 2
}
{ some other data... }
And want to match only body of this enum (between {}),
the match result i want is:
{
[EnumMember]
New = 0,
[EnumMember]
Normal = 1,
[EnumMember]
Disabled = 2
}
I make regex pattern like this:
public enum.*\w.*(?<enumBody>[\S|\s|]+\}{1})
but result is this:
{
[EnumMember]
New = 0,
[EnumMember]
Normal = 1,
[EnumMember]
Disabled = 2
}
{ some other data... }
Which is not what i expect because it also include next { some other data }
string which i dont want. I dont know how make pattern to stop after first }
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
?
使+
量词变得惰性。您不需要{1}
部分。Make the
+
quantifier lazy using?
. You don't need the{1}
part.尝试将 ^ 放在正则表达式的前面。
try putting ^ at the front of your regex.
如果这是整个正则表达式,则惰性量词将起作用,但如果您想防止匹配超出结束大括号,那么最好使用
[^}]:
如果你不想在左大括号之前包含空格,你可以在前面做同样的事情:
A lazy quantifier will work if that's the entire regular expression, but if you want to prevent the match from going past the end brace then it's better to explicitly disallow that character as part of the group by using
[^}]
:If you don't want to include whitespace before the open brace, you can do the same thing on the front: