简体   繁体   中英

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?"

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", "?" } { "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[] substrings = Regex.Split(source, stringSeparators);

But both are giving the result array without the occurrence of you in it.

Also, I want to split only on the whole word you . I don't want to split if you is a part of some other words. For example, in the case Hello you are so young , I want the result as { "Hello", "you", "so young" } . I don't want to split the word young to { "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|

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*");

This should work. Below is the output.

"Hello how are"

".Are"

"fine?.How old are"

"?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM