返回从正则表达式匹配只有一部分 [英] Returning only part of match from Regular Expression
问题描述
说我有字符串用户名: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?
每一个方法我都试过返回字符串用户名:firstname.surname那我必须做一个字符串替换上的用户名:为空字符串
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?
编辑:
较长的字符串可以包含帐户名:firstname.surname所以我为什么要匹配的用户名:藏汉字符串的一部分只得到了价值
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;
}
把<东西>
在一组括号中的开头(如(LT;东西> ...)
),使您可以获取使用从匹配值的东西
作为一个键(例如:从 m.Groups [东西。值
)
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屋!