使用正则表达式

时间:2018-04-16 11:11:27

标签: javascript regex

问题

我有一个长字符串,格式如下:

'{ "method": "POST", "url": "/iot/pipe/", "query": {}, "body": { "d": {"l": 1523737659, "n": "861359030665564", "b": 100, "v": "02.45", "t": 3, "dev": {"vr":7, "ae":1, "at":5, "ad":2, "as":4, "al":60, "tp":60, "tr":3, "tu":"http"://bus.mapit.me/iot/pipe/, "gt":50, "gm":120, "gh":400, "gs":3, "gr":2, "gg":1, "ua":0, "uu":"http"://bus.mapit.me/firmware/, "le":0, "lt":0, "sw":mapit2_v245, "sp":240, "rt":0, "sa":1}}}, "headers": { "host": "node_session_iot", "connection": "close", "content-length": "298", "accept": "*/*", "user-agent": "QUECTEL_MODULE", "content-type": "application/x-www-form-urlencoded" } }'

其中包含内部网址,如下例所示:

"uu":"http"://bus.mapit.me/firmware/

目的

我的目标是使用String.prototype.replace和Regex将其转换为以下内容(请注意""http"的末尾移动到字符串的末尾):

"uu":"http://bus.mapit.me/firmware/"

我尝试了什么

为了达到这个目的,我搜索了几个SO帖子,然后我到达了下面的代码,这个代码无效:

str.replace(/\"http\":(\w+)/g, "\"http:$1\"");

这对有问题的字符串没有任何作用。 我最接近的比赛是以下:

str.replace(/\"http\":/g, "\"http:\"");

这并不完全有用,因为它只是将\"移动到下一个位置,而不是将其移动到最后。

问题

我的正则表达式有什么问题?

2 个答案:

答案 0 :(得分:1)

工作代码:



var str = '{ "method": "POST", "url": "/iot/pipe/", "query": {}, "body": { "d": {"l": 1523737659, "n": "861359030665564", "b": 100, "v": "02.45", "t": 3, "dev": {"vr":7, "ae":1, "at":5, "ad":2, "as":4, "al":60, "tp":60, "tr":3, "tu":"http"://bus.mapit.me/iot/pipe/, "gt":50, "gm":120, "gh":400, "gs":3, "gr":2, "gg":1, "ua":0, "uu":"http"://bus.mapit.me/firmware/, "le":0, "lt":0, "sw":mapit2_v245, "sp":240, "rt":0, "sa":1}}}, "headers": { "host": "node_session_iot", "connection": "close", "content-length": "298", "accept": "*/*", "user-agent": "QUECTEL_MODULE", "content-type": "application/x-www-form-urlencoded" } }';
str = str.replace(/"http"([^,]*)/gm, '"http$1"')
console.log(str);




答案 1 :(得分:1)

问题是正则表达式与给定的URL不匹配。特别是捕获组中的\w+表示匹配一个或多个单词字符,其中单词字符是集合[a-zA-Z0-9_]中的任何字符。这与URL中的正斜杠不匹配,因为它们不被视为单词字符。

相反,您可以使用\S+来匹配任何非空白字符序列。另外,如果您需要多次使用它,请将结果分配回str(或其他变量)。

str = '"uu":"http"://bus.mapit.me/firmware/';
new_str = str.replace(/\"http\":(\S+)/g, "\"http:$1\"");
console.log(new_str);

输出:

"uu":"http://bus.mapit.me/firmware/"

您可以尝试here