简体   繁体   English

JavaScript中的正则表达式不匹配字符串吗?

[英]Regex in JavaScript is not matching a string?

I have this JavaScript code: 我有以下JavaScript代码:

var textareas = document.getElementsByTagName('textarea');
var content = textareas[0].value;
var reg = new RegExp(/^.*[[]#.+#[]].*$/mgi);
var res = content.match(reg); // always null 

The content var contains a long multiline string that contains patterns like [#some text goes here#] . content var包含一个长的多行字符串,该字符串包含类似[#some text goes here#] I tested the regex with some online testing tools and it works against the string. 我用一些在线测试工具测试了正则表达式,它可以对字符串进行测试。 Using the regex in JavaScript fails though - any idea why? 但是,在JavaScript中使用正则表达式会失败-知道为什么吗?

Thanks! 谢谢!

How about this? 这个怎么样?

var content = 'foo\nhead [#some text goes here#] tail\nbar';
var reg = new RegExp(/\[#.+#\]/mgi);
var res = content.match(reg);

On execution, res contains the string '[#some text goes here#]' . 执行时, res包含字符串'[#some text goes here#]'

Note that I have escaped [ and ] . 请注意,我已经逃脱了[] If they are not escaped, anything enclosed within them forms a character class . 如果不进行转义,则其中包含的所有内容都会构成一个字符类

You used [[] to escape [ , which is fine, but you can't use []] to escape ] because it the first ] ends the character class in the regex. 您使用[[]来转义[ ,这很好,但是您不能使用[]]来转义]因为它的第一个]结束了正则表达式中的字符类。 This works fine: 这很好用:

/^.*\[#.+#\].*$/mgi

In the case that you only want the single block and not the entire line, use: 如果只需要单个块而不是整个行,请使用:

/\[#.+#\]/mgi

这应该捕获散列之间的文本(例如,“此处有一些文本”):

var reg = /[^\[]*\[#([^\#]+)#\]/gims

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

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