仅从正则表达式返回匹配的一部分 [英] Returning only part of match from Regular Expression
问题描述
假设我在一个更大的字符串中包含字符串User Name:firstname.surname",我该如何使用正则表达式来获取 firstname.surname 部分?
Say I have the string "User Name:firstname.surname" contained in a larger string how can I use a regular expression to just get the firstname.surname part?
我尝试过的每种方法都会返回字符串用户名:名字.姓氏",然后我必须将用户名:"的字符串替换为空字符串.
Every method i have tried returns the string "User Name:firstname.surname" then I have to do a string replace on "User Name:" to an empty string.
在这里可以使用反向引用吗?
Could back references be of use here?
较长的字符串可能包含Account Name: firstname.surname",因此我想匹配字符串的User Name:"部分以获取该值.
The longer string could contain "Account Name: firstname.surname" hence why I want to match the "User Name:" part of the string aswell to just get that value.
推荐答案
我喜欢使用命名组:
Match m = Regex.Match("User Name:first.sur", @"User Name:(?<name>w+.w+)");
if(m.Success)
{
string name = m.Groups["name"].Value;
}
将 ?
放在括号中的组开头(例如 (?<something>...)
)允许您获得使用 something
作为键的匹配值(例如来自 m.Groups["something"].Value
)
Putting the ?<something>
at the beginning of a group in parentheses (e.g. (?<something>...)
) allows you to get the value from the match using something
as a key (e.g. from m.Groups["something"].Value
)
如果你不想麻烦地命名你的组,你可以说
If you didn't want to go to the trouble of naming your groups, you could say
Match m = Regex.Match("User Name:first.sur", @"User Name:(w+.w+)");
if(m.Success)
{
string name = m.Groups[1].Value;
}
然后获取匹配的第一件事.(请注意,第一个括号中的组位于索引 1
;匹配的整个表达式位于索引 0
)
and just get the first thing that matches. (Note that the first parenthesized group is at index 1
; the whole expression that matches is at index 0
)
这篇关于仅从正则表达式返回匹配的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!