简体   繁体   English

如何将带有方括号和正斜杠+变量的字符串转换为正则表达式?

[英]How to turn a String with square brackets and forward slashes + variables into a regex?

I've tried to get my head around regex, but I still can't get it. 我已经尽力让我绕过正则表达式,但是仍然无法理解。

I want to turn the following String + some variables into a regex: 我想将以下String +一些变量转换为正则表达式:

"[url href=" + objectId + "]" + objectId2 + "[/url]"

I tried the following, since I read somewhere that brackets and slashes need to be escaped: 我尝试了以下操作,因为我在某处读到需要将方括号和斜杠转义:

/\[url href=/ + objectId + /\]/ + objectId2 + /\[\/\url\]/g

But that isn't working. 但这不起作用。

I want to use it to replace the whole expression into HTML wherever it matches in a String. 我想使用它来将整个表达式替换为HTML,无论它在String中匹配什么位置。

You are correct that brackets and backslashes need to be escaped in a regular expression, but you can't create a regex by adding together regex literals like your /\\[url href=/ + objectId + /\\]/ attempt. 您是正确的,需要在正则表达式中转义括号和反斜杠,但是您无法通过将/\\[url href=/ + objectId + /\\]/尝试之类的正则表达式文字加在一起来创建正则表达式。 To build a regex dynamically like that you have to use string concatenation and pass the result to new RegExp() . 要像这样动态地构建正则表达式,必须使用字符串连接并将结果传递给new RegExp() So as a starting point for your text you'd need this: 因此,作为文本的起点,您需要这样做:

new RegExp("\\[url href=" + objectId + "\\]" + objectId2 + "\\[/url\\]")

Note all of the double-backslashes - that's because backslashes need to be escaped in string literals, so "\\\\[" creates a string containing a single backslash and then a bracket, which is what you want in your regex. 注意所有的双反斜杠-这是因为反斜杠需要在字符串文字中转义,因此"\\\\["创建一个包含单个反斜杠和一个方括号的字符串,这是您在正则表达式中想要的。

But if you want to extract the matched href and content for use in creating an anchor then you need capturing parentheses: 但是,如果要提取匹配的href和内容以用于创建锚,则需要捕获括号:

new RegExp("\\[url href=(" + objectId + ")\\](" + objectId2 + ")\\[/url\\]")

But that's still not enough for your purposes because objectId and objectId2 could (or will, given the first is a url) contain other characters that need to be escaped in a regex too, eg, .+?() , etc. So here's a function that can escape all of the necessary characters: 但这还不足以满足您的目的,因为objectIdobjectId2可能(或将是第一个是url)也包含其他需要在正则表达式中转义的字符,例如.+?()等。因此这是一个可以转义所有必需字符的函数:

function escapeStringForRegex(s) {
  return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

We can't just call that function on the whole thing, because you need unescaped parentheses for your capturing sub matches, so just call it on the two variables: 我们不能只在整个事情上调用该函数,因为您需要为捕获子匹配项使用未转义的括号,因此只需在两个变量上调用它即可:

var urlRegex = new RegExp("\\[url href=("
                          + escapeStringForRegex(objectId)
                          + ")\\]("
                          + escapeStringForRegex(objectId2)
                          + ")\\[/url\\]");

Kind of messy, but seems to do the job as you can see here: 有点杂乱无章,但您似乎可以在这里看到工作:

 function escapeStringForRegex(s) { return s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'); } function createAnchors(str, objectId, objectId2) { var urlRegex = new RegExp("\\\\[url href=(" + escapeStringForRegex(objectId) + ")\\\\](" + escapeStringForRegex(objectId2) + ")\\\\[/url\\\\]", "g"); return str.replace(urlRegex, "<a href='$1'>$2</a>"); } document.querySelector("button").addEventListener("click", function() { var str = document.getElementById("input").value; var objectId = document.getElementById("objectId").value; var objectId2 = document.getElementById("objectId2").value; document.getElementById("output").value = createAnchors(str, objectId, objectId2); }); 
 textarea { width : 100%; height: 80px; } 
 Input:<br><textarea id="input">This is just some text that you can edit to try things out. [url href=http://test.com.au?param=1]Test URL[/url]. Thanks.</textarea> ObjectId:<input id="objectId" value="http://test.com.au?param=1"><br> ObjectId2:<input id="objectId2" value="Test URL"><br> <button>Test</button> <textarea id="output"></textarea> 

Note that the above searches only for [url] s in your string that have the particular href and content specified in the objectId and objectId2 variables. 请注意,以上代码仅在字符串中搜索[url] ,它们具有在objectIdobjectId2变量中指定的特定href和内容。 If you just want to change all [url] s into anchors regardless of what href and text they contain then use this: 如果您只想将所有[url]更改为锚点,而不管它们包含的href和文本是什么,请使用以下命令:

.replace(/\[url href=([^\]]+)\]([^\]]+)\[\/url\]/g, "<a href='$1'>$2</a>")

Demo: 演示:

 function escapeStringForRegex(s) { return s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'); } function createAnchors(str) { return str.replace(/\\[url href=([^\\]]+)\\]([^\\]]+)\\[\\/url\\]/g, "<a href='$1'>$2</a>"); } document.querySelector("button").addEventListener("click", function() { var str = document.getElementById("input").value; document.getElementById("output").value = createAnchors(str); }); 
 textarea { width : 100%; height: 80px; } 
 Input:<br><textarea id="input">Testing. [url href=http://test.com.au?param=1]Test URL[/url]. Thanks. Another URL: [url href=https://something.com/test?param=1&amp;param2=123]Test URL 2[/url]</textarea> <button>Test</button> <textarea id="output"></textarea> 

就像是:

var rx = new RegExp('\\[url\\shref='+objectId+'\\]'+objectId2+'\\[\\/url\\]');
new RegExp("[url href=" + objectId + "]" + objectId2 + "[\url]")

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp

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

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