簡體   English   中英

C# - 獲取字符之間的所有單詞

[英]C# - Get All Words Between Chars

我有字符串:

string mystring = "hello(hi,mo,wo,ka)";

而且我需要將所有參數都放在括號中。 喜歡:

hi*mo*wo*ka

我試過了:

string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
     res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
     res += "*" + " " + z + " ";
}
return res;

但這會返回“,”之前的所有單詞。

(我需要返回之間

“(“ 和 ”,”

“,“ 和 ”,”

“,“ 和 ”)”

)

您可以嘗試使用\\\\(([^)]+)\\\\)正則表達式獲取括號中包含的單詞,然后使用Replace函數來讓,*

string res = "hello(hi,mo,wo,ka)";

var regex =  Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');

c#在線

結果

hi*mo*wo*ka

這邊走 :

  Regex rgx = new Regex(@"\((.*)\)");
  var result = rgx.Match("hello(hi,mo,wo,ka)");

Split方法有一個覆蓋,可讓您定義多個分隔符:

string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM