这是我的字符串:
================================================================================
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****
的行
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/