JavaScript RegExp对象 [英] JavaScript RegExp objects

查看:100
本文介绍了JavaScript RegExp对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用JavaScript编写一个简单的Markdown解析器。因此,我想检查 [link content] [link id] 语法。我使用以下代码:

I try to write a simple Markdown parser in JavaScript. Therefore I want to check for the [link content][link id] syntax. I use the following code:

data = data.replace( /\[(.*?)\][ ]*\[([0-9]+)\]/g, '<a href="$2">$1</a>' );

它运行良好,但现在我想用RegExp对象执行此操作。所以我设置了以下代码:

It works well, but now I want to do this with a RegExp object. So I set up the following bit of code:

var r = new RegExp( '\[(.*?)\][ ]*\[([0-9]+)\]', 'g' );
data = data.replace( r, '<a href="$2">$1</a>' );

但它不起作用。它甚至说我的正则表达式(自第一个例子以来工作得很好)无效:

But it doesn't work. It even says that my regular expression (which works since the first example does a good job) is invalid:


无法比拟的正则表达式

unmatched ) in regular expression

我认为它必须与我不知道的一些RegExp-object特性有关。
我做错了什么以及如何解决问题?

I think it must have to do with some RegExp-object peculiarities I am not aware of. What am I doing wrong and how can the problem be solved?

推荐答案

因为RegExp构造函数的第一个参数是一个字符串,而不是模式文字,你必须转义反斜杠,因为你需要模式中的文字反斜杠:

Because the first argument of the RegExp constructor is a string, not a pattern literal, you have to escape the backslashes, since you want literal backslashes in the pattern:

var r = new RegExp( '\\[(.*?)\\][ ]*\\[([0-9]+)\\]', 'g' );

这篇关于JavaScript RegExp对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆