[英]Split a string and keep separator string in c#
How can I split a string based on a string and have the resulting array contain the separators as well? 如何基于字符串拆分字符串,并使结果数组也包含分隔符?
Example: 例:
If my string = "Hello how are you.Are you fine?.How old are you?"
如果我的字符串=
"Hello how are you.Are you fine?.How old are you?"
And I want to split based on string "you", then result I want is an array with items { "Hello how are", "you", ".Are", "you", "fine?.How old are", "you", "?" }
我想基于字符串“ you”进行拆分,然后得到的结果是一个包含项的数组
{ "Hello how are", "you", ".Are", "you", "fine?.How old are", "you", "?" }
{ "Hello how are", "you", ".Are", "you", "fine?.How old are", "you", "?" }
. { "Hello how are", "you", ".Are", "you", "fine?.How old are", "you", "?" }
。
How can I get a result like this? 我如何获得这样的结果? I tried
String.Split
and 我尝试了
String.Split
和
string[] substrings = Regex.Split(source, stringSeparators);
But both are giving the result array without the occurrence of you
in it. 但是两者都给出了结果数组,却没有出现
you
。
Also, I want to split only on the whole word you
. 另外,我只想对整个单词
you
进行拆分。 I don't want to split if you
is a part of some other words. 如果
you
是其他字眼的一部分,我不想分裂。 For example, in the case Hello you are so young
, I want the result as { "Hello", "you", "so young" }
. 例如,在
Hello you are so young
的情况下,我希望结果为{ "Hello", "you", "so young" }
。 I don't want to split the word young
to { "you", "ng" }
. 我不想将
young
拆分为{ "you", "ng" }
。
You can put the seperator into a match group, then it will be part of the result array: 您可以将分隔符放入匹配组,然后它将成为结果数组的一部分:
string[] substrings = System.Text.RegularExpressions.Regex.Split(source, "(you)");
Output would be : 输出为:
"Hello how are ",
"you" ,
".Are ",
"you",
" fine?.How old are ",
"you",
"?"
Update regarding your additional question: Use word-boundaries around the keyword: 有关您的其他问题的更新:在关键字周围使用单词边界:
Split(source, "\\b(you)\\b");
\b(you)\b
以此拆分,您将获得结果。
regex replace : 正则表达式替换:
(you)
with |\\1|
(you)
与|\\1|
now you will have a string like this : 现在您将拥有一个像这样的字符串:
Hello how are |you|.Are |you| fine?.How old are |you|?
now you can simply split on |
现在您可以简单地拆分
|
Hope that helps 希望能有所帮助
string[] substrings = System.Text.RegularExpressions.Regex.Split(source,"\\s* you\\s*"); string []子字符串= System.Text.RegularExpressions.Regex.Split(source,“ \\ s *您\\ s *”);
This should work. 这应该工作。 Below is the output.
以下是输出。
"Hello how are" “你好”
".Are" “。是”
"fine?.How old are" “好吗?几岁了”
"?" “?”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.