This question has been asked on this site in two ways: first way was actually a different question; the OP wanted to keep the separators at the end/beginning of the resulting elements. The second question received an answer that included a Regex that I couldn't understand how to expand.
I'm looking for a way to split a string on separators, where the separators will be included as elements in the resulting array. Please explain how I can choose custom separators for this function (most possibly a Regex).
You can use a regex that specifies an empty expression with a lookahead or a lookbehind.
For example, let's say that you wish to split your string on any of these characters:
'(' ' ' ',' ')' '*' '/' '+' '-'
Then you can construct an expression that lists them in a lookahead or a lookbehind clause (i.e. (?=...)
or (?<=...)
), and split using Regex.Split
, like this:
string input = "12 / 34+(45-56)*678";
string pattern = "(?=[( ,)*/+-])|(?<=[( ,)*/+-])";
string[] substrings = Regex.Split(input, pattern);
foreach (string match in substrings) {
Console.WriteLine("'{0}'", match);
}
Running this produces the following output:
'12'
' '
'/'
' '
'34'
'+'
'('
'45'
'-'
'56'
')'
'*'
'678'
Note how all separators are included, along with spaces, parentheses, and operators.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다