简体   繁体   English

如何用正则表达式匹配特定的字符串?

[英]How to match a specific string with regular expression?

I have a string 我有一个弦

var txt="[!Qtextara1] Description1 [@Qtextara1]
        [!Qtextarea2] Description2 [@Qtextarea2]"

I want to match this string using regular expression The output should something like this. 我想使用正则表达式匹配此字符串输出应该是这样的。

{Qtextara1: Description1,  Qtextarea2: Description2} 

Is it possible with regular expression? 正则表达式可能吗? Please help me.. 请帮我..
Thanks in advance. 提前致谢。

You can use the following regex: 您可以使用以下正则表达式:

\[\!([\s\S]+?)\]\s+([\s\S]+?)\s*\[@\1\]

Explanation: 说明:

  • \\[\\! - Match literal [! -匹配文字[!
  • ([\\s\\S]+?) - Capture group 1 to match 1 or more characters inside [] (the tag name, we'll need that later on) ([\\s\\S]+?) -捕获组1以匹配[]中的1个或多个字符(标记名称,我们稍后将需要使用它)
  • \\]\\s+ - Literal ] and 1 or more whitespace symbols \\]\\s+ -文字]和1个或多个空格符号
  • ([\\s\\S]+?) - Capture group 2 to capture (even multiline) description ([\\s\\S]+?) -捕获组2以捕获(甚至多行)描述
  • \\s*\\[@\\1\\] - Match 0 or more whitespace, followed by a literal [@ , then a backreference to the first capture group (the tag name), and then a literal ] . \\s*\\[@\\1\\] -匹配0或多个空格,后跟文字[@ ,然后是对第一个捕获组(标记名称)的反向引用,再是文字]

See demo . 参见演示

 var re = /\\[\\!([\\s\\S]+?)\\]\\s+([\\s\\S]+?)\\s*\\[@\\1\\]/g; var test_str = '[!Qtextara1] Long Description Wi[th%^&*\\n(Abra# $]Cadabra~!~## 1 [@Qtextara1]\\n [!Qtextarea2] Description2 [@Qtextarea2]'; while ((m = re.exec(test_str)) !== null) { alert(m[1] + ", " + m[2]) } 

I got this 我懂了

txt.match(/(\[\![a-zA-Z0-9]*\]) ([a-zA-Z0-9]*) (\[\@[a-zA-Z0-9]*\])/);

That split in 3 part: 分为三部分:

Part 1 : 第1部分

txt.match(/(\[\![a-zA-Z0-9]*\]) ([a-zA-Z0-9]*) (\[\@[a-zA-Z0-9]*\])/)[1];
"[!Qtextara1]"

Part 2 : 第2部分

txt.match(/(\[\![a-zA-Z0-9]*\]) ([a-zA-Z0-9]*) (\[\@[a-zA-Z0-9]*\])/)[2];
"Description1"

Part 3 : 第3部分

txt.match(/(\[\![a-zA-Z0-9]*\]) ([a-zA-Z0-9]*) (\[\@[a-zA-Z0-9]*\])/)[3];
"[@Qtextara1]"

But that could be greatly improved. 但这可以大大改善。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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