简体   繁体   English

正则表达式匹配组之间的任意组合和数量的空格和换行符

[英]Regex to match any combination and number of whitespaces and linebreaks between groups

I am searching for a regex for my .NET program (C#) that ignores multiple whitespaces and linebreaks, and all combinations of thse between the matching groups.我正在为我的 .NET 程序 (C#) 寻找一个正则表达式,它忽略多个空格和换行符,以及匹配组之间的所有组合。

For example between the following two groups there can be \\r \\n \\t or spaces例如以下两组之间可以有\\r \\n \\t或空格

([A-Z])([A-Z0-9<])

This is some input with the desired output:这是一些具有所需输出的输入:

P\n0 -> P0 
N\n\rF -> NF
A\rP -> AP
A\r[space][space][space]\nP -> AP
E\n\r\nF -> EF
N\t\rF -> NF
R\t\n\r[space]F -> RF
A\rP -> AP

You may use \\s* (0 or more whitespaces) between the groups and once matched join the captured values:您可以在组之间使用\\s* (0 个或多个空格),一旦匹配就加入捕获的值:

var result = Regex.Matches(s, @"([A-Z])\s*([A-Z0-9<])")
        .Cast<Match>()
        .Select(x => $"{x.Groups[1].Value}{x.Groups[2].Value}")
        .ToList();

If there must be at least 1 whitespace between the two groups replace * with + .如果两组之间必须至少有 1 个空格,请将*替换为+

If your whitespace chars are limited to a specific list, replace \\s* with [\\t\\r\\n ]* (or [\\t\\r\\n ]+ ) to only match the whitespace you mention in the question.如果您的空格字符仅限于特定列表,请将\\s*替换为[\\t\\r\\n ]* (或[\\t\\r\\n ]+ )以仅匹配您在问题中提到的空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM