说明
问题的一部分是,\w
还包括所有字母a-z,所有数字0-9和底部_
。因此,如果您输入文字可以使用_
分隔符则表达式匹配\w+
会感到困惑
因为你有一个条件,允许下划线作为分隔符,我建议,而不是使用短手\w
是你,而不是定义字符类,你” d喜欢所需的文本和分隔符。
[0-9a-zA-Z]+
将任何顺序
[^a-zA-Z0-9]
这是一个否定的字符类,并且将匹配这是不alphebetical任何字符或数字
此正则表达式匹配匹配一个或多个alphebetical或数字所有的价值,并将允许范围广泛的分隔符。
^(?<pol>[0-9a-zA-Z]+)[^a-zA-Z0-9](?<fac>[0-9a-zA-Z]+\s[0-9a-zA-Z]+-[0-9a-zA-Z]+)[^a-zA-Z0-9](?<end>[0-9a-zA-Z]+)[^a-zA-Z0-9](?<op>[0-9a-zA-Z]+)
组
要匹配fac
组我假设领域将在以下格式:字母数字空间连字符数。
- 组0将获得整个匹配的字符串
- 的命名组将被创建,但是在图像1 = POL,2 = FAC,3 =端,和4 = OP。对不起,绘图软件无法处理命名的捕获组。
C#代码示例:
输入文本
12_B 99-23_9_23
11_a 11-11_1_11
22|b 22-22|2|22
33-c 33-33-3-33
44,d 44-44,4,44
代码
using System;
using System.Text.RegularExpressions;
namespace myapp
{
class Class1
{
static void Main(string[] args)
{
String sourcestring = "source string to match with pattern";
Regex re = new Regex(@"^(?<pol>[0-9a-zA-Z]+)[^a-zA-Z0-9](?<fac>[0-9a-zA-Z]+\s[0-9a-zA-Z]+-[0-9a-zA-Z]+)[^a-zA-Z0-9](?<end>[0-9a-zA-Z]+)[^a-zA-Z0-9](?<op>[0-9a-zA-Z]+)",RegexOptions.IgnoreCase | RegexOptions.Multiline);
MatchCollection mc = re.Matches(sourcestring);
int mIdx=0;
foreach (Match m in mc)
{
for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
{
Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
}
mIdx++;
}
}
}
}
匹配
$matches Array:
(
[0] => Array
(
[0] => 12_B 99-23_9_23
[1] => 11_a 11-11_1_11
[2] => 22|b 22-22|2|22
[3] => 33-c 33-33-3-33
[4] => 44,d 44-44,4,44
)
[pol] => Array
(
[0] => 12
[1] => 11
[2] => 22
[3] => 33
[4] => 44
)
[fac] => Array
(
[0] => B 99-23
[1] => a 11-11
[2] => b 22-22
[3] => c 33-33
[4] => d 44-44
)
[end] => Array
(
[0] => 9
[1] => 1
[2] => 2
[3] => 3
[4] => 4
)
[op] => Array
(
[0] => 23
[1] => 11
[2] => 22
[3] => 33
[4] => 44
)
)
谢谢! 但是,这不适用于这个例子... 12 | B 99-23 | 9 | 23 它必须匹配,直到下一个分隔符。在上面的例子将是这样的:^ 很抱歉,如果我不解释它很好 –
我已经(< pol> \ w +?)|(< fac>?)| |(< end> \ w +?)(< op> \ w +?)更新了我的答案,以包含适用于'|'字符的模式。你说过,“[分隔符可以是任何东西]”,但这没有多大意义。你期望什么分隔符?你需要处理混合分隔符吗?应如何匹配“12 | B 99_23 | 9 | 23”? –