在 C# 中解析字符串;有更清洁的方法吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/728018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing a string in C#; is there a cleaner way?
提问by Metro Smurf
C#, .NET 3.5
C#、.NET 3.5
This just smells of ugly to me, but I can't think of another way.
这对我来说只是闻起来很丑,但我想不出其他办法。
Given a string with the format of "Joe Smith (jsmith)" (sans quotes), I'd like to parse out just the 'jsmith' string within the parenthesis. I've come up with this:
给定一个格式为“Joe Smith (jsmith)”(无引号)的字符串,我只想解析括号内的“jsmith”字符串。我想出了这个:
private static string DecipherUserName( string user )
{
if( !user.Contains( "(" ) )
return user;
int start = user.IndexOf( "(" );
return user.Substring( start ).Replace( "(", string.Empty ).Replace( ")", string.Empty );
}
Other than my (un)healthy aversion to RegEx, is there a simpler way to parse out the substring?
除了我对 RegEx 的(不)健康的厌恶之外,还有没有更简单的方法来解析子字符串?
Edit:To clarify, the string to parse will always be of: "Joe Smith (jsmith)" (sans quotes).
编辑:澄清一下,要解析的字符串将始终为:“Joe Smith (jsmith)”(无引号)。
采纳答案by paxdiablo
You shouldn't need the first replace since you can just add 1 to the "(" position.
您不需要第一次替换,因为您只需将 1 添加到“(”位置。
private static string DecipherUserName (string user) {
int start = user.IndexOf( "(" );
if (start == -1)
return user;
return user.Substring (start+1).Replace( ")", string.Empty );
}
回答by Dillie-O
Since the IndexOf function will return -1 when the value doesn't exist, you could do things slightly different...
由于当值不存在时 IndexOf 函数将返回 -1,因此您可以做一些稍微不同的事情......
private static string DecipherUserName( string user )
{
int start = user.IndexOf( "(" );
if (start > -1)
{
return user.Substring( start ).Replace( "(", string.Empty ).Replace( ")", string.Empty );
}
else
{
return user;
}
}
回答by Shea
Regexes are so useful that you'll save yourself a ton of heartache biting the bullet and learning them. Not the whole shebang, just the basics.
正则表达式是如此有用,以至于您咬紧牙关学习它们会省去很多心痛。不是整个shebang,只是基础知识。
One regex that'll work is "\w+\((.*)\)" - jsmith would be in Match.Groups[1].
一种有效的正则表达式是“\w+\((.*)\)”——jsmith 将在 Match.Groups[1] 中。
One easy way to pick up regexes is to find a website that'll let you type in a regex and some text then spit out the matches...
获取正则表达式的一种简单方法是找到一个网站,让您输入正则表达式和一些文本,然后吐出匹配项...
回答by Daniel Brückner
Kind of a hack ... ^^
有点像黑客...... ^^
return user.Substring(user.IndexOf('(') + 1).TrimEnd(')');
If user
contains no opening parenthesis, IndexOf()
returns -1
, we add one, get zero, and SubString()
returns the whole string. TrimEnd()
will have no effect unless the user's name ends with a closing parenthesis.
如果不user
包含左括号,则IndexOf()
返回-1
,我们加一,得到零,并SubString()
返回整个字符串。TrimEnd()
除非用户名以右括号结尾,否则将无效。
If user
contains a opening parenthesis, IndexOf()
returns its index, we skipp the opening parenthesis by adding one, and extract the rest of the string with Substring()
. Finally we remove the closing parenthesis with TrimEnd()
.
如果user
包含一个IndexOf()
左括号,则返回其索引,我们通过添加一个来跳过左括号,并使用 提取字符串的其余部分Substring()
。最后,我们用 删除右括号TrimEnd()
。
回答by MartinStettner
I'd use
我会用
int start=user.IndexOf('(');
if (start != -1) {
end = user.IndexOf(')', start);
return user.Substring(start+1,end-start-1);
} else
return user;
But this is just a cosmetic change: using characters in IndexOf is a little bit faster, and using the Substring method seems to express more exactly what should be done (and the method is more robust if you have multiple pairs of parentheses...)
但这只是表面上的变化:在 IndexOf 中使用字符要快一点,而使用 Substring 方法似乎更准确地表达了应该做什么(如果您有多对括号,该方法更健壮......)
That said, Daniel L's method (using String.Split
) might be simpler (but doesn't deal very well with malformed strings and has to construct a string array).
也就是说,Daniel L的方法(使用String.Split
)可能更简单(但不能很好地处理格式错误的字符串并且必须构造一个字符串数组)。
All in all, I'd suggest you to overcome your aversion to regular expressions, since that situation is exactly what they're intended for :-) ...
总而言之,我建议您克服对正则表达式的厌恶,因为这种情况正是它们的目的:-) ...
回答by Matthew Sposato
If the user string is always in the form "Joe Smith (jsmith)", this should work.
如果用户字符串始终采用“Joe Smith (jsmith)”形式,这应该可以工作。
private static string DecipherUserName(string user)
{
string[] names = user.Split(new char[] {'(', ')'});
return names.Length > 2 ? names[1] : user;
}
And if the user string is always "Joe Smith (jsmith)", this will always work.
如果用户字符串始终是“Joe Smith (jsmith)”,这将始终有效。
private static string DecipherUserName(string user)
{
return "jsmith";
}
The second entry for humor purposes only.
第二个条目仅用于幽默目的。