Dans général cas, vous devez utiliser un analyseur; si vous voulez juste pour partager et préserver le délimiteur, s'il vous plaît, jetez un oeil à Regex.Split
:
string source = "[-3*4+20-0.5/-4.1]";
//TODO: specify the delimiters:
// If you want more delimiters, e.g. (,), [, ] etc.
// for, say, 9*[(456+789)/(95-2.96)-3]
// just add them into the array
char[] delimiters = new char[] { '*', '+', '-', '/' };
string pattern = "(" + string.Join("|", delimiters
.Select(item => Regex.Escape(item.ToString()))) + ")";
string[] result = Regex
.Split(source.TrimStart('[').TrimEnd(']'), pattern) // (...) preserves delim
.Select(item => item.Trim()) // <- if you want to trim each item
.Where(item => !string.IsNullOrEmpty(item))
.ToArray();
// -, 3, *, 4, +, 20, -, 0.5, /, -, 4.1
Console.Write(string.Join(", ", result));
Modifier: Pour les grands textes que vous pouvez mettre en œuvre la scission manuellement:
public static List<string> SplitPreserveSeparators(string source, char[] delimiters) {
if (null == source)
throw new ArgumentNullException("source")
else if (delimiters == null)
throw new ArgumentNullException("delimiters")
int start = 0;
int index = -1;
List<string> items = new List<string>();
while ((index = source.IndexOfAny(delimiters, start)) >= 0) {
string value = source.Substring(start, index - start);
if (!string.IsNullOrEmpty(value))
items.Add(value);
items.Add(source.Substring(index, 1));
start = index + 1;
}
if (start < source.Length)
items.Add(source.Substring(start));
return items;
}
et utilisation il
string source = "[-3-4+20-0.5/-4.1]";
char[] delimiters = new char[] { '*', '+', '-', '/' };
List<string> result = SplitPreserveSeparators(
source.TrimStart('[').TrimEnd(']'),
delimiters);
Console.Write(string.Join(", ", result));
Veuillez mettre à jour votre question avec le scénario le plus défavorable et le résultat attendu. Peut-être [-0.5 * 1,000.5 + 5,000- (7 + 5)] => ??? –