[英]Split string on * character regex
我試圖將'*'字符上的字符串分成兩部分,我有以下句子: This is * test string
我已經寫了這段代碼
Regex regex = new Regex(@"\\*");
string[] substrings = regex.Split(text);
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
但是我得到以下輸出:
'T'h'i's' 'i's'....
但我渴望:
'This is ' ' test string'
任何想法如何糾正我的正則表達式?
編輯:我的句子可能有多個“ *”字符,在這種情況下,我將需要三個句子,例如:
This is * test *
“我的句子中可能有多個'*',String.split可以工作嗎?”
是的,您還可以使用String.Split()
實現您想要的工作:
var text = "This is * test *";
var substrings = text.Split('*');
這將為您提供一個包含三個字符串的數組。
“這是 ”
“測試”
”
最后一個字符串是一個空字符串,您可以使用接受StringSplitOptions
值的方法重載將其忽略:
var substrings =
text.Split(new[] {'*'}, StringSplitOptions.RemoveEmptyEntries);
從您的正則表達式中刪除雙轉義符:
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);
輸出量
'This is '
' test '
' more '
' test'
根據以下代碼的預期輸出,可能會有所幫助:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.