使用正则表达式在两个子串之间获取值

时间:2022-11-27 18:41:20

If I have a string "Param1=value1;Param2=value2;Param3=val3", how can I get the value between the substrings "Param2=" and the next semicolon (or end of string, whichever comes first)?"

如果我有一个字符串“Param1 = value1; Param2 = value2; Param3 = val3”,我如何得到子字符串“Param2 =”和下一个分号(或字符串的结尾,以先到者为准)之间的值?“

4 个解决方案

#1


"Param\d+=([^;]*)" will capture the contents between = and ; in group 1

“Param \ d + =([^;] *)”将捕获=和之间的内容;在第1组中

#2


/Param2=([^;]+)/

#3


You can either use a character class that excludes ; (as others have answered), or you can use a non-greedy match anything:

你可以使用排除的字符类; (正如其他人已经回答的那样),或者你可以使用非贪婪的比赛:

/Param2=(.*?);/

#4


You can use this string to place all of the values into the Matches collection of the Regex class

您可以使用此字符串将所有值放入Regex类的Matches集合中

string regex = "Param[0-9]*?=(?<value>.*?)(;|$)"

#1


"Param\d+=([^;]*)" will capture the contents between = and ; in group 1

“Param \ d + =([^;] *)”将捕获=和之间的内容;在第1组中

#2


/Param2=([^;]+)/

#3


You can either use a character class that excludes ; (as others have answered), or you can use a non-greedy match anything:

你可以使用排除的字符类; (正如其他人已经回答的那样),或者你可以使用非贪婪的比赛:

/Param2=(.*?);/

#4


You can use this string to place all of the values into the Matches collection of the Regex class

您可以使用此字符串将所有值放入Regex类的Matches集合中

string regex = "Param[0-9]*?=(?<value>.*?)(;|$)"