regex 如何使用正则表达式提取子串,操作子串并重新插入它?

zwghvu4y  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(109)

我有一个Odata查询字符串(为了便于阅读,我将字符串分成了3行,但实际上只有一行)

/odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20
PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z%20and%20
ForeignBarcode%20eq%20'abcd1234'

在JavaScript中,我需要像这样操作购买日期参数,

PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z

date(PurchaseDate)%20eq%202023-11-20

(that is:添加带括号的日期函数,将nIN更改为eq并删除时间)

问:是否有一个regex one liner来完成此操作?

以下是我的尝试

//define the input

let input =
"/odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20PurchaseDate%20nIN%202023-02-02T23%3A00%3A00.000Z%20and%20ForeignBarcode%20eq%20'abcd1234"

//extract the date (using look behind and look ahead)
let rdate = /(?<=PurchaseDate%20nIN%20)\d{4}-\d{2}-\d{2}(?=T\d{2}%3A\d{2}%3A\d{2}.\d{3}Z)/
let date = rdate.exec(input)

//use regex and some string manipulation to replace the orignal substring
input.replace(/PurchaseDate%20nIN%20\d{4}-\d{2}-\d{2}T\d{2}%3A\d{2}%3A\d{2}.\d{3}Z/,`date(PurchaseDate%20eq%20${date[0]})`)

//result
// /odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20date(PurchaseDate)%20eq%202023-02-02)%20and%20ForeignBarcode%20eq%20'abcd1234
jecbmhm3

jecbmhm31#

我会避免使用正则表达式来编码字符串。请考虑先解析URL,然后替换需要替换的内容。您可以先使用URL类来解析它。

let path = "/odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z%20and%20ForeignBarcode%20eq%20'abcd1234'";
let url = new URL(path, "http://example.com");
let filter = url.searchParams.get("$filter");
filter = filter.replace(/PurchaseDate nIN (\d{4}-\d{2}-\d{2})T.*?Z/, "date(PurchaseDate) = $1");
url.searchParams.set("$filter", filter);
console.log(filter);
console.log(url.pathname + url.search);
qgelzfjb

qgelzfjb2#

我们可以在捕获组的帮助下尝试以下正则表达式替换:

var input = "PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z";
var output = input.replace(/PurchaseDate%(\d+).*?%(\d{6})-(\d{2})-(\d{2})T.*?\.\d{3}[A-Z]/, "date(PurchaseDate)%$1eq%$2-$3-$4");
console.log(output);

相关问题