[英]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(',','*');
结果
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.