我想将类似于“001A”的字符串拆分成“001”和“A”。
Match match = Regex.Match(s, @"^(\d+)(.+)$");
string numeral = match.Groups[1].Value;
string tail = match.Groups[2].Value;
string[] data = Regex.Split("001A", "([A-Z])");
data[0] -> "001"
data[1] -> "A"
Regex.Split("001A", "([A-Z])")
,或者将组移除(作为分隔符)。 - Kobi String s = "123XYZ456ABC";
String[] arr = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
System.out.println(Arrays.toString(arr));
// prints "[123, XYZ, 456, ABC]"
正如您所看到的,这将在\d
后跟\D
或反之处分割字符串。它使用正向和负向环视来查找拆分位置。
StringBuilder sb = new StringBuilder();
Regex regex = new Regex(@"\d*");
MatchCollection matches = regex.Matches(inputString);
for(int i=0; i < matches.count;i++){
sb.Append(matches[i].value + " ");
}
然后将正则表达式更改为匹配字符并执行相同的循环。
而且如果有更多类似 001A002B
的内容,那么你可以
var s = "001A002B";
var matches = Regex.Matches(s, "[0-9]+|[A-Z]+");
var numbers_and_alphas = new List<string>();
foreach (Match match in matches)
{
numbers_and_alphas.Add(match.Value);
}
.
匹配任何字符,您应该限制为\w
或[a-zA-Z]
。" - knittl。
就可以了。由于问题没有足够的细节,所以我选择了这个方案。 - Kobi