freepascal正则表达式替换 [英] freepascal regexp replace
问题描述
在FreePascal/Lazarus中是否有一种简便的RegExp替换方法?
Is there an easy way to do a RegExp replace in FreePascal/Lazarus?
到处寻找我可以很容易地进行比赛,但是我一直在努力寻找可以进行搜索和替换的功能.
Hunting around I can see that I can do a match fairly easily, but I'm struggling to find functions to do a search and replace.
我要实现的目标如下.
- 我已将XML文件加载到SynEdit组件中.
- 该XML文件的开头有十进制
- DTD存放在单独的文件中.
- 我不想将两者合并在一个文件中,但是我想在编辑XML时对其进行验证.
- 我正在将XML读取到字符串变量中,并且我想在XML内容和XML内容之间的DTD中插入一个可解析和验证的临时字符串变量(以创建具有自包含DTD的兼容XML)./li>
- I have an XML file loaded into a SynEdit component.
- The XML file has a decalaration at the start
- The DTD is held in a seperate file.
- I don't want to combine the two in one file, but I do wantto validate the XML as it is being editted.
- I'm reading the XML into a string variable and I want to insert the DTD between the and the XML content in a temporary string variable (to create a compliant XML with self contained DTD) that can be parsed and validated.
所以基本上我有:
<?Line1?>
Line2
Line3
我想进行RegExp类型搜索,并用'<?Line1?> \ n<![DTD \ nINFO WOULD \ nGOHER \ n!]'替换为'<?Line1?>'给我:
And I want to do a RegExp type search and replace for '<?Line1?>' replaceing with '<?Line1?>\n<![DTD\nINFO WOULD\nGO HERE\n!]' to give me:
<?Line1?>
<![DTD
INFO WOULD
GO HERE
!]
Line2
Line3
例如在PHP中,我将使用:
For example in PHP I would use:
preg_replace('/(<\?.*\?>)/im','$1
<![DTD
INFO WOULD
GO HERE
!]',$sourcestring);
但是FreePascal/Lazarus似乎没有一组等效的regexp函数-只是一个简单/基本的RegExp匹配函数.
But there doesn't seem to be an equivalent set of regexp functions for FreePascal / Lazarus - just a simple/basic RegExp match function.
还是有一种不使用正则表达式的简单方法-我不想假设声明始终在第1行上的正确位置上-只是使事情复杂化.
Or is there an easier way without using regular expressions - I don't want to assume that the declaration is always there in the correct position on Line 1 though - just to complicate things.
谢谢
FM
推荐答案
据我所知,PerlRegEx单元与Free Pascal不兼容.但是您可以使用Free Pascal随附的RegExpr单元.
As far as I know, the PerlRegEx unit isn't compatible with Free Pascal. But you can use the RegExpr unit, which comes with Free Pascal.
如果我的理解正确,您想用替代词代替.这是一个简单的示例,您可以根据需要进行调整.
If I understand correctly, you want a replacement with substitution. Here is a simple example that you can adapt to your need.
{$APPTYPE CONSOLE}
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
uses
regexpr;
var
s: string;
begin
s := 'My name is Bond.';
s := ReplaceRegExpr(
'My name is (\w+?)\.',
s,
'His name is $1.',
TRUE // Use substitution
);
WriteLn(s); // His name is Bond.
ReadLn;
end.
这篇关于freepascal正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!