Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用正则表达式匹配一组单词_Regex - Fatal编程技术网

Regex 使用正则表达式匹配一组单词

Regex 使用正则表达式匹配一组单词,regex,Regex,我有一个长字符串,格式如下: ' Random Key : Random Value\n Random Long Key : Random Long Value\n...' 等等。 我想把它改成 Random Value:Random Key, Random Long Value:Random Long Key,... 通过使用regex。我可以用一个单词来匹配 \w+ 但是为了匹配不止一个单词,我正在做 \w+(\s\w+)* 但这并没有给我想要的结果。您可以使

我有一个长字符串,格式如下:

' Random Key         : Random Value\n Random Long Key     : Random Long Value\n...'
等等。 我想把它改成

Random Value:Random Key, Random Long Value:Random Long Key,...
通过使用regex。我可以用一个单词来匹配

\w+
但是为了匹配不止一个单词,我正在做

\w+(\s\w+)*

但这并没有给我想要的结果。

您可以使用这段代码来查找键值对:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        var regex = new Regex(@"\s*(?<key>(\w+\s?\w+)*)\s*:\s*(?<val>(\w+\s?\w+))\s*");
        var input = @" Key         : Value\n Long Key     : Long Value\n...";
        Console.WriteLine(regex.Replace(input, "${key}:${val}").Replace("\\n", ", "));
    }
}
使用系统;
使用System.Text.RegularExpressions;
公共课程
{
公共静态void Main()
{
var regex=new regex(@“\s*(?(\w+\s?\w+)*)\s*:\s*(?(\w+\s?\w+))\s*”);
变量输入=@“键:值\n长键:长值\n…”;
WriteLine(regex.Replace(输入,${key}:${val}”).Replace(“\\n”,“,”));
}
}
诀窍是匹配“任意数量的(至少一个单词字符、一个可选空格和至少另一个单词字符)”,这会为我们找到带空格的键。但最短的无空格键是两个字符


我承认转义的换行符不会被正则表达式替换,但这样表达式和代码都相当简单。

如果您的
\n
确实是字符串的一部分,您可以这样匹配和替换它:

/(?:\s*([^\\]+?)\s*:\s*([^\\]+?)\s*)+\\n/g
并用

$1:$2,
$1:$2,

如果有逐行匹配,则更容易,因为可以使用多行匹配:

/^\s*(.+?)\s*:\s*(.+?)\s*$/mg
并将其替换为

$1:$2,
$1:$2,

.

其他答案没有一个对我完全有效,因为它们在最后一个单词后一直与空格相匹配。按预期工作的正则表达式是


(\w+(?:\s\w+*)

示例会很有帮助。您碰巧使用哪种编程语言?我的问题是某些键确实包含spaces@user6068049好的,我换了正则表达式。我认为C#是一种编程语言。在另一个平台上,regex语法可能略有不同。