举个例子如下图
[test Wed Jul 07 07:10:24.917274 2021] [wsgi:error] [pid 8] [remote 192.168.5.75:52770] /usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py:1020: InsecureRequestWarning: Unverified HTTPS request is being made to host '172.20.140.242'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
我想提取开头的 [test Wed Jul 07 07:10:24.917274 2021],把 [] 中的作为一个变量,而去掉 [] ,也就是提取Wed Jul 07 07:10:24.917274 2021
那么写法就是
^\[(?:test (?<time>[^\]]*))\]
可能我这个有人说有别的写法,是的但是我这个比较通用,
我这里是以[开头 以]结尾,但是你也可以以[开头 以:结尾。
!!!!注意,这里的y也就是以什么结尾,匹配的是第一处出现的地方。
解释一下,^表示开始,首先匹配\[
然后中间部分就是(?:test (?<time>[^\]]*)),看下图
?:后面到(这中间的部分就是以什么开始,
后面^\] 指的是以]结束,\]这么写是为了转义
*别忘了
这样,匹配的就是第一次出现的],而不是最后出现的]