使用RegEx从文件中提取文本


Extract text from a file using RegEx

我有一个文本文件,其中包含以下数据,

dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add a1 a2 arcn dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add a2 a1 arcn h dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add a1 a2 arc dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add a2 a1 arc h f %%EndResource The text i want to grap showpage

所以我希望所有的文本都在%%EndResourceshowpage之间。

任何帮助都将不胜感激。。。。

尝试此regex

/%%EndResource(.*)showpage/g

要获得这两者之间的值,请使用$1

这应该能在中工作

/(?<=%%EndResource).*?(?=showpage)/s

在Regexr 上查看

(?<=%%EndResource)是一个后备断言,它确保"%%EndResource"在您想要获得的部分之前。

(?=showpage)是一个前瞻性断言,它确保"%%EndResource"跟随您想要获得的部分。

.匹配任何字符(包括换行符,因为末尾有s修饰符)

*?匹配任意数量的字符和空字符串(!),但尽可能少(因为?

此处不需要正则表达式。

$start = strpos($the_string, "%%EndResource") + count("%%EndResource");
$end = strpos($the_string, "showpage")
$result = substr($the_string, $start, $end - $start);

如果您想释放空间,最终添加trim()

下面的正则表达式将捕获组中需要的内容,然后您可以稍后访问。

正则表达式如下:

%%EndResource(.*?)showpage

您可以看到如何使用本教程访问regex组中的数据。