php - 字符串的特殊 preg_match

标签 php regex string preg-match

这是我的字符串:

================================================================================
                                       INPUT FILE
================================================================================
NAME = CO-c0m1.txt
|  1> ! HF def2-TZVP opt numfreq

|  2> 

|  3> % scf

|  4>      convergence tight

|  5> end

|  6> 

|  7> * xyz 0 1

|  8> C 0 0 0

|  9> O 0 0 1

| 10> *

| 11> 
| 12>                          ****END OF INPUT****
================================================================================

我想得到这个输出:

! HF def2-TZVP opt numfreq
% scf
     convergence tight
end

* xyz 0 1
C 0 0 0
O 0 0 1
*

我已经尝试了大约 5 个小时,但做不到,请帮忙,这是我的预匹配:

$regx = '/INPUT FILE...................................................................................(.*?)........................END OF INPUT/s';
      if(preg_match($regx, $source[$i], $matches)) {
        $input[$i] = preg_replace('/\s\s\s\s+/', "\n", $matches[1]);
      }

我是正则表达式的新手,似乎很难。 有人可以帮助我吗,在此先感谢:)!

最佳答案

您需要一个正则表达式来匹配以 | 开头,后跟一些空格,然后是一个或多个数字,然后是 > 的行,您只需要后面的文本这个前缀。

正则表达式为:/^\|\s*\d+>(.*)$/m。它包含一个用于您需要的文本的捕获组。 preg_match_all()将捕获片段放入 $matches[1]:

preg_match_all('/^\|\s*\d+>(.*)$/m', $source[$i], $matches);
echo(implode("\n", $matches[1]));

然后您可以通过其他方式(array_pop()array_filter() 等)删除包含 ****END OF INPUT**** 的行

实际检查:https://3v4l.org/hUEBk

regex 解释:

/             # regex delimiter
    ^         # match the beginning of the line
    \|        # match '|' (it needs to be escaped because it is a meta-character)
    \s        # match a whitespace character (space, tab)
    *         # the previous (a whitespace) can appear zero or more times
    \d        # match a digit (0..9)
    +         # the previous (a digit) can appear one or more times
    >         # match '>'
    (         # begin of a capturing group
      .*      # match any character, any number of times
    )         # end of the capturing group
    $         # match the end of the line
/             # regex delimiter
m             # multiline (regex modifier); check the regex against each line of the input string

阅读更多关于 Perl-Compatible Regular Expressions in PHP 的信息.

关于php - 字符串的特殊 preg_match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274285/

相关文章:

java - 如何编写正则表达式以及如何在java中制作更多一组?

c++ - 向字符串中添加一个字符

java - Android,微调项目不显示

php - 如何测试 PHP 应用程序的 IPv6 兼容性?

php - XAMPP 测试版 13 : Slow mysql connect

php - Docker Redis 连接被拒绝

r - 如何删除括号并将内容保留在 Data Frame 中

PHP 函数看不到第二个参数的值

r - 迭代地提取跨说话轮次的重复单词形式

linux - 如何在搜索特定字符串后使用 grep 和 sed 替换子字符串?