是否可以按空格拆分字符串但將名稱保留在一起?
例子:
"1 23565 john smith 01/01/2021 another"
預期的:
string[] {"1", "23565", "john smith", "01/01/2021", "another"}
在這種情況下,名稱是字符串中不包含數字的任何單詞。“名稱”詞總是在“數字”詞之前和之後。
您可以嘗試正則表達式,例如
using System.Text.RegularExpressions;
...
string source = "1 23565 john smith 01/01/2021 another";
string[] result = Regex.Split(source, @"(?<=\P{L})\s+|\s+(?=\P{L})");
// Let's have a look:
Console.WriteLine(string.Join(", ", result));
結果:
1, 23565, john smith, 01/01/2021, another
我在這裡放置了(?<=\P{L})\s+|\s+(?=\P{L})
模式:
(?<=\P{L})\s+ - look behind (not a letter)
then one or more whitespaces
| - or
\s+(?=\P{L}) - one or more whitespaces and
then (look ahead) not a letter
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句