使用正则表达式帮我拆分字符串

3

请帮我解决这个问题。我想把“-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] = ""

请帮助我。

附言:我正在使用.NET 2.0。

谢谢。

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

我想把它分成“destination”和“C:\Program Files\Release”

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

请帮助我。谢谢。


你好,我用字符串 @"-destination=C:\Program Files\Release" 进行了测试,但结果不准确,我不明白为什么结果的长度为1。我认为这是因为字符串中有一个空格。我想将其拆分为 "destination" 和 "C:\Program Files\Release"。请帮助我。谢谢。 - Leo Vo
5个回答

5
不要使用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;

在.NET正则表达式中,永远不要使用索引来分组...你可以为某个原因命名分组。想象一下,如果有人稍后通过添加另一组括号轻微地更改正则表达式,那么你就必须在所有的索引处进行更改。- 改用组名。 - Timothy Khouri
我只在非常简单的情况下使用索引,比如这种情况(只有一个或两个捕获组,没有嵌套组等)。否则,我同意使用名称可以使正则表达式更加健壮且易于理解。 - Lucero
你好,我测试过这个字符串:@"-destination=C:\Program Files\Release",但是结果不准确。我认为这是因为字符串中有一个空格。我想将其拆分为 "destination" 和 "C:\Program Files\Release"。 - Leo Vo

3
尝试使用以下代码(已更新添加 Regex.Split ):
string victim = "-action=1";
string[] stringSplit = victim.Split("-=".ToCharArray());
string[] regexSplit = Regex.Split(victim, "[-=]");

编辑: 以您的例子为例:

string input = @"-destination=C:\Program Files\Release -action=value";
foreach(Match match in Regex.Matches(input, @"-(?<name>\w+)=(?<value>[^=-]*)"))
{
    Console.WriteLine("{0}", match.Value);
    Console.WriteLine("\tname  = {0}", match.Groups["name" ].Value);
    Console.WriteLine("\tvalue = {0}", match.Groups["value"].Value);
}
Console.ReadLine();

当然,如果您的路径包含 - 字符,这段代码就会出现问题。

3
在.NET正则表达式中,您可以为自己的组命名。
string pattern = @"^-(?<MyKey>\S+)=(?<MyValue>\S+)$";
Regex regex = new Regex(pattern);
string myText = "-action=1";

然后进行“匹配”,按照组名获取相应的值。
Match theMatch = regex.Match(myText);
if (theMatch.Success)
{
    Console.Write(theMatch.Groups["MyKey"].Value); // This is "action"
    Console.Write(theMatch.Groups["MyValue"].Value); // This is "1"
}

0

使用string.split()有何问题?

string test = "-action=1";
string[] splitUp = test.Split("-=".ToCharArray());

我承认,尽管这仍然给您可能比您想在拆分数组中看到的参数更多...
[0] = ""
[1] = "action"
[2] = "1"

有什么问题吗?你不能免费获得输入验证,而且它可能会以不同的方式处理事情(想象一下“-range=1-2”)。 - Lucero
同意,但使用正则表达式并不是免费的,正如OP所看到的,构建适当的正则表达式字符串并不是一项微不足道的任务。我只是建议一个相对可行的替代方案,它不依赖于了解未知的内容(参见OP的编辑)。 - ZombieSheep

0
在他的演讲《正则表达式精通》中,Mark Dominus向学习Perl作者(也是StackOverflow用户)Randal Schwartz提供了以下有用的规则:
  • 当你知道要保留什么时,请使用捕获或m//g [或regex.Match(...)]。
  • 当你知道要丢弃什么时,请使用split
同时,他还提到了属性

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接