我正在尝试使用StringUtils.removeAll方法删除字符串的一部分并保留其他部分:
SELECT regexp_replace(';;test;;;', '(;;)*$'), regexp_replace(';;test;;;;', '(;;)*$');
┌────────────────┬────────────────┐
│ regexp_replace │ regexp_replace │
├────────────────┼────────────────┤
│ ;;test; │ ;;test │
└────────────────┴────────────────┘
(1 row)
这是我的正则表达式
String locations = [{"code":"b","name":"Beavercreek"},{"code":"bj","name":"Beavercreek Juvenile"},...]
它没有删除任何内容,我无法正确使用正则表达式?
答案 0 :(得分:0)
看起来你试图解析的字符串是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"]