Regex删除访问令牌模式并替换为空字符串



我正试图从JSON响应中找到并删除访问令牌模式。

{
"name":"any name",
"access_token":"xxx-xxxxx-1234-45rf",
"some_data":"some random data",
"Api_key":"1234-cd34-xxx-xxxx"
}

我正在尝试下面的regex

".*-.*-.*"

但是它从字符串中删除了整行,例如

"access_token":"xxx-xxxxx-1234-45rf",

我想达到的结果如下:

{
"name":"any name",
"access_token":"",
"some_data":"some random data",
"Api_key":""
}

上面的access_token只是一个虚拟的,实际的密钥可以是不同长度的带连字符的字符串。

您可以在replaceAll函数中使用正则表达式。这将用一个空字符串替换acces_token和它的值。

String jsonString = "{ "name":"any name", "access_token":"xxx-xxxxx-1234-45rf", "some_data":"some random data", "Api_key":"1234-cd34-xxx-xxxx" }";
jsonString.replaceAll("("access_token":)(")(.*?)(",) ", "")

试试这个:

String json = "{ "name":"any name", "access_token":"xxx-xxxxx-1234-45rf", "some_data":"some random data", "Api_key":"1234-cd34-xxx-xxxx" }";
json = json.replaceAll(".{3}-.{5}-[\d]{4}-[\w]{4}", "");

看它在这里工作

您需要的代码是:

String json = "{ "name":"any name", "access_token":"xxx-xxxxx-1234-45rf", "some_data":"some random data", "Api_key":"1234-cd34-xxx-xxxx" }";
json = json.replaceAll("("access_token")\s*:\s*"[^"]+"", "$1:""");

regex回升引用的项目名称(在括号内,因此它被存储为第1组),其次是一些可选的空格字符,一个冒号,一些可选的空格字符和任何非空引用价值。所有这些都被带引号的项目名称(来自第1组!)替换,后面跟着一个冒号和一个空的引号值。

JAVA

import required packages

import java.util.regex.Matcher;
import java.util.regex.Pattern;
json string
public static void main(String[] args) {
Pattern p = Pattern.compile(":\"(.*?)\"");
String json = "{"name":"any name", "access_token":"xxx-xxxxx-1234-45rf", "some_data":"some random data", "Api_key":"1234-cd34-xxx-xxxx"}";
Matcher m = p.matcher(json);
StringBuffer buf = new StringBuffer();
while (m.find()) {
m.appendReplacement(buf, String.format(":"%s"", m.group(1)).replaceAll(".*-.*-.*", ":"""));
}
m.appendTail(buf);
System.out.println(buf); // output: {"name":"any name", "access_token":"", "some_data":"some random data", "Api_key":""}
}
static method
private static String removeToken(String content) {
Pattern p = Pattern.compile(".*-.*-.*");
return p.matcher(content).replaceAll("");
}
JavaScript

无嵌套对象

const obj = {
"name": "any name",
"access_token": "xxx-xxxxx-1234-45rf",
"some_data": "some random data",
"Api_key": "1234-cd34-xxx-xxxx"
};
for (const [key, value] of Object.entries(obj)) {
obj[key] = value.replace(/.*-.*-.*/, '');
}
console.log(obj);

:多层嵌套对象

const obj = {
"name": "any name",
"access_token": "xxx-xxxxx-1234-45rf",
"some_data": "some random data",
"Api_key": "1234-cd34-xxx-xxxx",
"obj": {
"111name": "any name",
"access_token": "xxx-xxxxx-1234-45rf",
"some_data": "some random data",
"Api_key": "1234-cd34-xxx-xxxx"
}
};
const restructure = obj => {
return Object.keys(obj).reduce((data, key) => {
let value = obj[key];
if (typeof value === 'string') {
value = value.replace(/.*-.*-.*/, '');
} else if (typeof value === 'object') {
value = restructure(value)
}
data[key] = value;
return data
}, {})
}
console.log(restructure(obj));

最新更新