简体   繁体   English

C# - 获取字符之间的所有单词

[英]C# - Get All Words Between Chars

I have string:我有字符串:

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

And i need to get all arguments in brackets.而且我需要将所有参数都放在括号中。 Like:喜欢:

hi*mo*wo*ka

I tried that:我试过了:

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;

But that returns all words before ",".但这会返回“,”之前的所有单词。

(I need to return between (我需要返回之间

"(" and "," “(“ 和 ”,”

"," and "," “,“ 和 ”,”

"," and ")" “,“ 和 ”)”

) )

You can try to use \\\\(([^)]+)\\\\) regex get the word contain in brackets,then use Replace function to let , to *您可以尝试使用\\\\(([^)]+)\\\\)正则表达式获取括号中包含的单词,然后使用Replace函数来让,*

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

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

c# online c#在线

Result结果

hi*mo*wo*ka

This way :这边走 :

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

Split method has an override that lets you define multiple delimiter chars: 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