[英]JavaScript regex symbol occurence
I have some problem with regex in JS. 我在JS中遇到了正则表达式问题。 I wrote my regular expression:
我写了我的正则表达式:
/^([A-Z]+)\s+([^\s]+)\s+([^\s]+)\s(\[.*\])\s+(.+)$/g
But it gives wrong result with one example: 但是用一个例子给出了错误的结果:
WARN 2016-01-19 13:17:32,051 [localhost-startStop-1] Duplicate property values for key Data\ Df : [ Date from] and [ Starting Day]
I want regex to divide the string in a such parts: 我希望正则表达式将字符串分成这样的部分:
WARN
2016-01-19
13:17:32,051
[localhost-startStop-1]
Duplicate property values for key Data\ Df : [ Date from] and [ Starting Day]
And everything OK, except last 2 parts. 一切正常,除了最后两个部分。 There I got:
我到了:
[localhost-startStop-1] Duplicate property values for key Data\ Df : [ Date from]
and [ Starting Day]
Why? 为什么? I want to divide that part of string by first ] occurrence.
我想将字符串的那一部分除以]出现。 Don't know why it takes the second.
不知道为什么要花第二秒钟。
PS: Here is the example: https://regex101.com/r/wG5xV6/2 PS:这是示例: https : //regex101.com/r/wG5xV6/2
Thanks. 谢谢。
You need to restrict the .*
(that matches zero or more characters other than a newline, as many as possible) with a lazy dot matching .*?
您需要使用与
.*?
匹配的惰性点来限制.*
(与换行符相匹配的零个或多个字符,并尽可能地匹配) .*?
that matches zero or more characters other than a newline, as few as possible: 与换行符以外的零个或多个字符匹配,且尽可能少:
^([A-Z]+)\s+([^\s]+)\s+([^\s]+)\s(\[.*?\])\s+(.+)$
^^^
See the regex demo 见正则表达式演示
You can also shorten the pattern a bit by replacing [^\\s]
with \\S
: 您还可以通过将
[^\\s]
替换为\\S
稍微缩短模式:
^([A-Z]+)\s+(\S+)\s+(\S+)\s(\[.*?\])\s+(.+)$
var re = /^([AZ]+)\\s+(\\S+)\\s+(\\S+)\\s(\\[.*?\\])\\s+(.+)$/gm; var str = 'INFO 2016-01-20 08:03:21,113 [C3P0PooledConnectionPoolManager[identityToken->1bqu9pa9eq1cqr515yzwu7|6c240779]-HelperThread-#0] Connection to \\'rander\\' established. Notifying listeners...\\nWARN 2016-01-19 13:17:32,051 [localhost-startStop-1] Duplicate property values for key Data\\ Df : [ Date from] and [ Starting Day]'; while ((m = re.exec(str)) !== null) { document.body.innerHTML += "<pre>"+ JSON.stringify([m[1],m[2],m[3],m[4], m[5]], 0, 4) + "</pre>"; }
You can try this: 您可以尝试以下方法:
^(.*?)(\\s*?)(\\S*?)(\\s*?)(\\S*?)(\\s*?)(\\[.*?\\])(\\s*)(.*?)$
Also change \\S
with .
也改变
\\S
用.
\\S
means not sapce. \\S
表示不安全。 ?
means get less. The rules of this sentence can be expressed as follows 这句话的规则可以表示如下
begin + word + space + word + space + word + space + word + space + word + end
It must find first ]
,so we use ?
begin + word + space + word + space + word + space + word + space + word + end
它必须先找到]
,所以我们使用?
to find it. 找到它。 if u want to change the format of this sentence,you can replace it use
($1)\\r($3)\\r($5)\\r($7)\\r($9)
or other. 如果要更改此句子的格式,则可以使用
($1)\\r($3)\\r($5)\\r($7)\\r($9)
或其他替换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.