Help me break a string using RegExp

please help me in this problem. I want to split "-action = 1" into "action" and "1".

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

I do not know why the result has a length = 4.

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

Please help me.

P / S: I am using .NET 2.0.

Thank.

Hello, I tested using the line: @ "- destination = C: \ Program Files \ Release", but it has the wrong result, I don’t understand why result length = 1. I think because it has a space in the line.

I want to split it into "destination" and "C: \ Program Files \ Release"

Additional information: This is my requirement: -string1 = string2 → divide it into: string1 and string2. In string1 and string2 do not contain characters: '-', '=', but they can contain spaces.

, . .

+3
5

(, 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

split, Match, Groups ( 1 2).

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;
+5

.NET Regex .

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"
}
+3

string.split()?

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

, , split...

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

In his speech , The Regular Expression Wizard , Mark Dominus attributes, the following is a useful rule for learning Perl author (and StackOverflow user ) Randall Schwartz:

  • Use the capture or m//g[or regex.Match(...)] when you know you want to save.
  • Use splitwhen you know what you want to throw away.
0
source

Source: https://habr.com/ru/post/1729209/


All Articles