为什么这个javascript正则表达式返回null?



我需要提取一个JSON字符串,它位于一个更大的字符串(我知道,糟糕的API响应,我只需要处理)。无论如何,我构建了一个regex来读取{}中的所有内容,并且它在所有测试情况下都有效,除了下面代码片段中的实际API响应。

知道为什么它不起作用以及如何使它起作用吗?

let dd = 'Error: Internal JSON-RPC error.n{n  "code": 3,n  "message": "execution reverted: This limited season is sold out. Please wait for the next season.",n  "data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000004154686973206c696d6974656420736561736f6e20697320736f6c64206f75742e20506c65617365207761697420666f7220746865206e65787420736561736f6e2e00000000000000000000000000000000000000000000000000000000000000"n}';
alert(RegExp(/{.*}/).exec(dd))

您需要添加一个s标志作为RegExp构造函数的第二个参数:

s - ("dotAll")允许。匹配换行符

let dd = 'Error: Internal JSON-RPC error.n{n  "code": 3,n  "message": "execution reverted: This limited season is sold out. Please wait for the next season.",n  "data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000004154686973206c696d6974656420736561736f6e20697320736f6c64206f75742e20506c65617365207761697420666f7220746865206e65787420736561736f6e2e00000000000000000000000000000000000000000000000000000000000000"n}';
alert(RegExp('{.*}', 's').exec(dd))

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp

内容在多行之间不匹配,因此可以使用/s修饰符来包含新行。当使用Regexp语法(/{.*}/sRegexp('{.*}','s')相同)时,也不需要Regexp():

alert(/{.*}/s.exec(dd))

let dd = 'Error: Internal JSON-RPC error.n{n  "code": 3,n  "message": "execution reverted: This limited season is sold out. Please wait for the next season.",n  "data": "0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000004154686973206c696d6974656420736561736f6e20697320736f6c64206f75742e20506c65617365207761697420666f7220746865206e65787420736561736f6e2e00000000000000000000000000000000000000000000000000000000000000"n}';
alert(/{.*}/s.exec(dd))

试试这个匹配所有内容的表达式

/{[sS]*}/.exec(dd)

您创建的那个不能工作,因为它包含换行符n

使用.match()的另一种方法实际上将返回与您想要提取的字符串的匹配,该字符串位于{花括号}内部。两个标志s用于搜索新行,g用于全局搜索

dd.match(/{(.*)?}/sg)[0]

Result{n "code": 3,n "message": "execution reverted: T…0000000000000000000000000000000000000000000000"n}

相关内容

  • 没有找到相关文章

最新更新