I am attempting to split a string in two on the '*' character, I have the following sentence : This is * test string
and I have written this code
Regex regex = new Regex(@"\\*");
string[] substrings = regex.Split(text);
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
But I get the following output:
'T'h'i's' 'i's'....
But I desire:
'This is ' ' test string'
Any ideas how to correct my regex?
Edit : My sentence may have more than one '*' character, in which case i would need three sentences, eg :
This is * test *
"I may have more than one '*' in a sentence, will String.split work?"
Yes, you can achieve what you're trying to do with String.Split()
as well:
var text = "This is * test *";
var substrings = text.Split('*');
This will give you an array with three strings.
"This is "
" test "
""
The final string is an empty string, which you can omit by using the method overload that accepts a StringSplitOptions
value:
var substrings =
text.Split(new[] {'*'}, StringSplitOptions.RemoveEmptyEntries);
Remove the double escape from you regular expression:
Regex regex = new Regex(@"\*");
...
Regex regex = new Regex(@"\*");
String text = "This is * test * more * test";
string[] substrings = regex.Split(text);
foreach (String match in substrings)
Console.WriteLine("'{0}'", match);
Output
'This is '
' test '
' more '
' test'
As per your expected output below code might help:
string text = "This is * test string";
Regex regex = new Regex(@"\*");
string[] substrings = regex.Split(text);
string output = "";
foreach (string match in substrings)
{
output += match;
}
Console.WriteLine(output);
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.