gpt4 book ai didi

javascript - 如何使用正则表达式来匹配以下字符串?

转载 作者:行者123 更新时间:2023-12-03 05:20:06 27 4
gpt4 key购买 nike

我对正则表达式有点陌生,以前没怎么用过。

我正在尝试匹配以下字符串String A并将其替换为String B

字符串A:

+ ANYTHING_NO_SPACES.prototype.ANYTHING_NO_SPACES = function()
{
ANYTHING
}

字符串B:

ANYTHING_NO_SPACES.prototype.function_segments.ANYTHING_NO_SPACES.push(function())
{
ANYTHING
})

ANYTHING_NO_SPACES 表示任何内容都可以放在那里,没有空格

ANYTHING 表示可以放任何东西,空格等。

我还想忽略新行,因此新行与空格或什么都没有相同。

编辑:这是我到目前为止所得到的:

(\+ \w+.prototype\.\w+ = function\(\)( |\n){([\S\s]*?)})

我不知道如何完成最后一点..将 string 更改为 string b

关于如何完成这个任务有什么想法吗?

最佳答案

具体操作方法如下:

var output = input.replace(
/(^|\n)\s*\+\s*(\w+)\.prototype\.(\w+)\s*=\s*function\(\)\n{([\s\S]+?\n})/g,
"$1$2.prototype.function_segments.$3.push(function())\n{$4)"
);

该正则表达式中有一些值得注意的事情:

  • (^|\n) 是字符串的开头或新行
  • [\s\S] 匹配包括换行在内的任何字符
  • [\s\S]+? 是非贪婪的,因此它不会一次性捕获多个函数
  • 只有当您的代码正确缩进时,此方法才有效:由于代码未解析,我们依靠位于行开头的 } 来检测函数结束

演示:

document.getElementById("output").innerHTML = document.getElementById("input").innerHTML.replace(
/(^|\n)\s*\+\s*(\w+)\.prototype\.(\w+)\s*=\s*function\(\)\n{([\s\S]+?\n})/g,
"$1$2.prototype.function_segments.$3.push(function())\n{$4)"
);
INPUT:
<pre id=input>
+ ANYTHING_NO_SPACES.prototype.ANYTHING_NO_SPACES = function()
{
ANYTHING
}
+ blabla.prototype.hop = function()
{
ANYTHING
TOO
}
</pre>
OUTPUT:
<pre id=output>

关于javascript - 如何使用正则表达式来匹配以下字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41426339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com