[英]Regular expression to split string and number
I have a string of the form: 我有一个形式的字符串:
codename123
Is there a regular expression that can be used with Regex.Split()
to split the alphabetic part and the numeric part into a two-element string array? 是否有一个正则表达式可以与Regex.Split()
一起使用,将字母部分和数字部分分成两个元素的字符串数组?
I know you asked for the Split
method, but as an alternative you could use named capturing groups: 我知道您要求使用Split
方法,但作为替代方法,您可以使用命名捕获组:
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)");
var match = numAlpha.Match("codename123");
var alpha = match.Groups["Alpha"].Value;
var num = match.Groups["Numeric"].Value;
splitArray = Regex.Split("codename123", @"(?<=\p{L})(?=\p{N})");
将在Unicode字母和Unicode数字之间分割。
Regex is a little heavy handed for this, if your string is always of that form. 如果你的字符串总是那种形式,那么正则表达式对此有点沉重。 You could use 你可以用
"codename123".IndexOfAny(new char[] {'1','2','3','4','5','6','7','8','9','0'})
and two calls to Substring. 以及对Substring的两次调用。
A little verbose, but 有点冗长,但是
Regex.Split( "codename123", @"(?<=[a-zA-Z])(?=\d)" );
Can you be more specific about your requirements? 你能更具体地了解你的要求吗? Maybe a few other input examples. 也许还有一些其他的输入例子。
IMO, it would be a lot easier to find matches, like: IMO,找到比赛会更容易,比如:
Regex.Matches("codename123", @"[a-zA-Z]+|\d+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
rather than to use Regex.Split
. 而不是使用Regex.Split
。
Another simpler way is 另一种更简单的方法是
string originalstring = "codename123";
string alphabets = string.empty;
string numbers = string.empty;
foreach (char item in mainstring)
{
if (Char.IsLetter(item))
alphabets += item;
if (Char.IsNumber(item))
numbers += item;
}
好吧,只是一行: Regex.Split("codename123", "^([az]+)");
this code is written in java/logic should be same elsewhere 这段代码是用java / logic编写的,应该在别处相同
public String splitStringAndNumber(String string) {
String pattern = "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(string);
if (m.find()) {
return (m.group(1) + " " + m.group(2));
}
return "";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.