說明
問題的一部分是,\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」? –