duanpa1980 2018-11-15 15:54
浏览 60
已采纳

preg_match()失败了

I need to check if a string contains a table, which is like this:

+--------+------+-------+
| <info>number</info> | <info>char</info> | <info>word</info>  |
+--------+------+-------+
| 1      | a    | alfa  |
| 2      | b    | beta  |
| 3      | c    | gamma |
+--------+------+-------+

I do not know the number of columns, nor the number of rows, but this is the structure of the table.

This regex works with Unix, but not with Windows

[\+\-]+[
](\|(\s+<info>[^<]+<\/info>\s+\|)+)[
](\+|\-)+[
]((\|(\s+[^\|]+\s+\|)+[
])+)(\+|\-)+

This is a test:
https://regex101.com/r/TSxSd7/1

And this is a part of code:

    $regexRowDivider = '[\+\-]+';
    $regexHeader = '(\|(\s+<info>[^<]+<\/info>\s+\|)+)';
    $regexRow = '\|(\s+[^\|]+\s+\|)+';
    $regexRows = '((' . $regexRow . '[
])+)';
    $regexTable = $regexRowDivider . '[
]' . $regexHeader . '[
]' . $regexRowDivider . '[
]' . $regexRows . $regexRowDivider;

    preg_match('/' . $regexTable . '/', $output, $matches);

After hours of testing, I can not figure out what the problem is. Do you have any idea? preg_last_error() returns a 0 (no errors)

  • 写回答

1条回答 默认 最新

  • duanli4146 2018-11-16 06:17
    关注

    This is probably because you're only accepting one of either or , and Windows uses both ( ). You can match both of these newline characters (and more) by using \R.

    I removed a few pieces of complexity, so it doesn't enforce spaces in every cell:

    [+-]+\R+\|(\s*<info>[^<]+<\/info>\s*\|)+\R+[+-]+\R+\|([^|]+\|)+\R+[+-]+
    
    \---/   \------------------------------/   \---/   \----------/   \---/
    Line             Column Headers            Line      Contents     Line
    

    Try it online

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应