gpt4 book ai didi

c# - 帮助我使用 RegExp 拆分字符串

转载 作者:行者123 更新时间:2023-11-30 13:34:46 25 4
gpt4 key购买 nike

请帮我解决这个问题。我想将“-action=1”拆分为“action”和“1”。

string pattern = @"^-(\S+)=(\S+)$";
Regex regex = new Regex(pattern);
string myText = "-action=1";
string[] result = regex.Split(myText);

我不知道为什么结果的长度为 4。

result[0] = ""
result[1] = "action"
result[2] = "1"
result[3] = ""

请帮帮我。

P/S:我使用的是 .NET 2.0。

谢谢。

你好,我测试了字符串:@"-destination=C:\Program Files\Release"但它的结果不准确,我不明白为什么结果的长度 = 1。我想是因为它在字符串中有一个空格.

我想把它拆分到“目的地”和“C:\Program Files\Release”

更多信息:这是我的要求:-string1=string2 -> 拆分为:string1 & string2。在 string1 和 string2 中不包含字符:'-'、'=',但它们可以包含空格。

请帮帮我。谢谢。

最佳答案

不使用split,只使用Match,然后根据索引(索引1和2)从Groups集合中获取结果。

Match match = regex.Match(myText);
if (!match.Success) {
// the regex didn't match - you can do error handling here
}
string action = match.Groups[1].Value;
string number = match.Groups[2].Value;

关于c# - 帮助我使用 RegExp 拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2100534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com