目前我很困惑! 我一直试图解决这个问题,似乎无法破解它。 我甚至无法在Google上找到答案。
目前我正在使用我在Javascript中编写的正则表达式:
((?: {4,}|\t+)(?:.*))简单地说,它匹配4 +空格的所有内容或textarea中的1 +标签。 是的,你觉得这听起来很熟悉? 这就是Stack Overflow对代码块的作用。 现在,我遇到了一个问题。
基本上我想要替换textarea中找到的所有这些实例,但首先我要将它们备份到数组中。 现在,我不确定如何抓住找到的每个匹配项,并将其插入到数组中。
这是我到目前为止:
.replace(/((?: {4,}|\t+)(?:.*))/gi, function (m, g1, g2) { return //STUCK HERE }); //Matches Bold所以简单地说,我只想抓住在textarea中找到的所有匹配(缩进或4个空格),然后我想将匹配的内容添加到数组中。 我该怎么做呢? 请帮忙!
currently I am very confused! I have been trying to solve this for a while, and can't seem to crack it. I can't even find an answer on Google.
Currently I am using this Regex I wrote in Javascript:
((?: {4,}|\t+)(?:.*))Simply, it matches everything that is 4+ spaces out or 1+ tabs out in a textarea. Yea, that sounds familiar you say? It is simply what Stack Overflow does for codeblocks. Now, I have run in to an issue.
Basically I am wanting to replace all of these instances found in the textarea, but first I want to back them up to an array. Now, I am not sure how I grab each match found, and insert it in to the array.
Here is what I have so far:
.replace(/((?: {4,}|\t+)(?:.*))/gi, function (m, g1, g2) { return //STUCK HERE }); //Matches BoldSo simply, I just want to grab all matches found in a textarea (Either indented or 4 spaces) and then I would like to add the contents of the match to an array. How would I go about doing this? Please Help!
最满意答案
你可以用一颗子弹击中两个目标:
var items = []; var re = /((?: {4,}|\t+)(?:.*))/g; textarea.value = textarea.value.replace(re, function ($0, $1) { items.push($1); return 'replacement'; });如果你想获得代码块,那么:
var codeLines = []; var reMarkers = /\{\{(.*?)\}\}/g; var reCodeBlocks = /((?: {4,}|\t+)(?:.*))/g; var text = textarea.value; // save and remove code blocks text = text.replace(reCodeBlocks, function ($0, $1) { var marker = '{{' + codeLines.length + '}}'; codeLines.push($1); return marker; }); // revert to previous state text = text.replace(reMarkers, function ($0, $1) { return codeLines[parseInt($1, 10)]; });You can hit two targets with one bullet:
var items = []; var re = /((?: {4,}|\t+)(?:.*))/g; textarea.value = textarea.value.replace(re, function ($0, $1) { items.push($1); return 'replacement'; });If you want to get the code blocks back then:
var codeLines = []; var reMarkers = /\{\{(.*?)\}\}/g; var reCodeBlocks = /((?: {4,}|\t+)(?:.*))/g; var text = textarea.value; // save and remove code blocks text = text.replace(reCodeBlocks, function ($0, $1) { var marker = '{{' + codeLines.length + '}}'; codeLines.push($1); return marker; }); // revert to previous state text = text.replace(reMarkers, function ($0, $1) { return codeLines[parseInt($1, 10)]; });更多推荐
发布评论