【问题标题】:Removing Strings using Regex issues使用正则表达式问题删除字符串
【发布时间】:2017-09-22 15:19:48
【问题描述】:

我正在尝试使用 StringUtils.removeAll 方法删除部分字符串并保留其他部分:

String locations = [{"code":"b","name":"Beavercreek"},{"code":"bj","name":"Beavercreek Juvenile"},...]

这是我的正则表达式

StringUtils.removeAll(result.get("locations").toString(),"\\{\"code\":,\"name\":^[a-zA-Z0-9_.-]*$\"\"\\}");

它没有删除任何东西,我无法正确地得到正则表达式?

【问题讨论】:

  • 您要删除什么?为什么你的正则表达式包含^$(它们代表字符串结尾的开始,所以在正则表达式中间使用它们没有多大意义)。
  • 另外你为什么使用正则表达式而不是正确的 JSON 解析器,它可以让你将此字符串转换为 JSON 对象,你可以修改你想要的方式?
  • ,\"name\":\"[a-zA-Z0-9_.-]*?\" 如果你想删除 name:value;\"code\":\"[a-zA-Z0-9_.-]*?\", 如果你想删除 code:value。但我会接受@Pshemo 的建议!

标签: java json regex


【解决方案1】:

看起来您尝试解析的字符串是 JSON,所以我建议使用 JSON 解析器。不过,为了完整起见,我也会为您提供一个使用正则表达式的解决方案。

import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {

public static void main(String[] args) throws Exception {
    String locations = "[{\"code\":\"b\",\"name\":\"Beavercreek\"},{\"code\":\"bj\",\"name\":\"Beavercreek Juvenile\"}]";

    // Parsing Using a JSON Parser (Recommended)
    ObjectMapper jsonMapper = new ObjectMapper();
    Model[] modelArray = jsonMapper.readValue(locations, Model[].class);

    for(Model model : modelArray) {
        System.out.println(model.toString());
    }

    // Parsing Using String.replaceAll with regex
    locations = locations.replaceAll("\\{\"code\":", "");
    locations = locations.replaceAll("\"name\":", "");

    System.out.println(locations.replaceAll("\\}", ""));
}

static class Model {
    private String code;
    private String name;

    public Model() { }

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("%s, %s", code, name);
    }
}
}

输出:

// JSON Parsing
b, Beavercreek
bj, Beavercreek Juvenile
// REGEX Parsing
["b","Beavercreek","bj","Beavercreek Juvenile"]

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2014-11-07
    • 1970-01-01
    • 2018-01-26
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    相关资源
    最近更新 更多