我想使用SAAM
(我在Delphi XE4和XE5中编码)从以下文本中提取SAAMI
和RegEX
:
RegEx = 'Name:\s?(.*),Family:\s?(.*)';
例如,我有这样的文字:
Name: SAAM
Family: SAAMI
我编写了此代码,并使用MatchAgain
TPerlRegEx
方法匹配两个正则表达式('Name:\s?(.*)'
和'Family:\s?(.*)'
)。
...
var
RX: TPerlRegEx;
const
RegEx = 'Name:\s?(.*),Family:\s?(.*)';
begin
RX := TPerlRegEx.Create;
try
RX.RegEx := RegEx;
RX.Subject := mmo1.Text;// The mmo1.text value is "Name: SAAM and Family: SAAMI"
if RX.Match then
begin
repeat
ShowMessage('Name is :' + RX.Groups[1]);
ShowMessage('Family is :' + RX.Groups[2]);
until not RX.MatchAgain;
end;
finally
RX.Free;
end;
...
为什么这段代码不起作用?
答案 0 :(得分:3)
我将我的代码更改为此代码,它对我来说正常工作(几乎:-))。
示例文字:
Junk text :-)
Junk text :-)
Junk text :-)
Name: SAAM
Junk text :-)
Junk text :-)
Junk text :-)
Junk text :-)
Junk text :-)
Family: SAAMI
Junk text :-)
Junk text :-)
Junk text :-)
新代码:
var
RX: TPerlRegEx;
i: Integer;
const
RegEx = 'Name:\s?(.*)|Family:\s?(.*)';
begin
i := 1;
RX := TPerlRegEx.Create;
try
RX.RegEx := RegEx;
RX.Subject := mmo1.Text;
if RX.Match then
begin
repeat
case i of
1:
ShowMessage('Name is: ' + RX.Groups[i]);
2:
ShowMessage('Family is: ' + RX.Groups[i]);
end;
Inc(i);
until not RX.MatchAgain;
end;
finally
RX.Free;
end;
结果:
Name is: SAAM
Family is: SAAMI