dqndc26628 2013-03-29 04:26
浏览 16
已采纳

使用正则表达式检查PHP中的特定模式

I am trying to create the following regular expression in PHP to match the following:

[2013-01-01 12:34:12.123] [USERNAME] something

I am able to get part of the first part but I am new to regex in php, any help is appreciated.

Important note: any space above could be one space or more.

(This is what I got so far)

/^[\[][0-9]{4}-[0-9]{2}-[0-9]{2}]/

I am using this tool to test that my regex match: http://www.pagecolumn.com/tool/pregtest.htm (just want to confirm that it is an okay tool).

Update: to clerify more, something could be any amount of text, white spaces above could be any amount of white spaces and USERNAME could be any amount of text as well.

  • 写回答

3条回答 默认 最新

  • duanhao7786 2013-03-29 05:16
    关注

    Since your format has delimiters (the []s), you don't need the checks that the other answers provide. Instead you can simply use

    \[([^\]]*)\]\s+\[([^\]]*)\]\s+(.*)
    

    which breaks down to

    \[([^\]]*)\] // Capture all non-] chars within [ and ]; this is the date
    \s+ // some space
    \[([^\]]*)\] // Capture all non-] chars within [ and ] again; this is USERNAME
    \s+ // some space
    (.*) // Capture all the text after; this is something
    

    You can walk through this regex step-by-step using Debuggex.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度