Using regex to check on a specific pattern in 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.
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.
[d{4}-d{2}-d{2}s+[d:.]+]s+[w+]s+something
http://rubular.com/r/BPGvFN4kwi
You're not specific about your rules. For example the very first part probably needs to be a date, but the regex can match 13
for the month. Is that okay? Also what makes a valid "USERNAME" or "something?"
/^[([0-9]{4}-[0-9]{2}-[0-9]{2})s+([0-9]+:[0-9]+:[0-9]+(?:.[0-9]+)?)+]s+[([^]]+)]s+(.+)/
With comments:
/^
[ # "[" is a special char and should be escape
([0-9]{4}-[0-9]{2}-[0-9]{2}) # Use brackets for group and capture (see $matches in php function)
s+ # One or move space chars (space, tab, etc.)
([0-9]+:[0-9]+:[0-9]+(?:.[0-9]+)?)+ # "(?: )" is a group without capturing
]
s+
[([^]]+)] # "[^]]+" - one or more any char except "]"
s+
(.+) # One or more any char
/x
PS: you can use "d" instead of "[0-9]" and (in this case; for flexibility) you can use "+" ("one or more char" specifier) instead of "{4}" or "{2}".
PPS: http://www.pagecolumn.com/tool/pregtest.htm contains bug (incorrect handles backslash), try another service.
链接地址: http://www.djcxy.com/p/77080.html上一篇: 正则表达式匹配两个单词而不匹配其他单词
下一篇: 使用正则表达式来检查PHP中的特定模式