简体   繁体   中英

Optional element in regex in java

I have this pattern:

"^([\\d.]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\d+|\\S+)"

That I use it on the following apache access log entry:

127.0.0.1 - - [16/Jul/2011:20:29:14 +0100] "GET /TestWebPages/MScAIS-SEWN-Search-Optimisation.html HTTP/1.1" 200 5569

Sometime after the 7th element I might or might not have something. Eg

127.0.0.1 - - [16/Jul/2011:20:29:14 +0100] "GET /TestWebPages/MScAIS-SEWN-Search-Optimisation.html HTTP/1.1" 200 5569 –

Sometimes I have the - at the end and sometime it just doesn't exists.

How can add this to my pattern? I tried using (\\\\S{0}) but it did not work!

尝试添加: (\\\\s–){0,1}这意味着您可以出现零次或一次“ - ”

Try the question mark:

\S? (alternative \S{0,1})

or for multiple occurence the asterisk:

\S* (alternative \S{0,})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM