java 正则和连接json

网友投稿 245 2022-09-04

java 正则和连接json

前面已经写了不少关于C# 怎么使用正则,有兴趣,可以翻译成java代码。

以图片为例子:

import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexUtil { public static String regexImg(String html){ if(StrKit.isBlank(html)){ return html; } Pattern pattern=Pattern.compile(""); Matcher matcher=Pattern.matcher(html); while (matcher.find()) { String img=matcher.group(); String src=findAttrInHtmlTag(img, "src"); } return html; } public static String findAttrInHtmlTag(String tag,String attr){ if(tag==null||attr==null) return null; Pattern pattern=Pattern.compile("\\b"+attr+"\\s*=\\s*(['\"]?)(?.*?)\\1"); Matcher matcher=pattern.matcher(tag); if(matcher.find()){ return matcher.group("value"); } return null; }}

连接Json:

Record就是一个实体对象:

public static String concatJson(Record record,String[] columnNames, boolean keepEmptyColumn) { if (record == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append("{"); if (columnNames == null) { columnNames = record.getColumnNames(); } for (int i = 0; i < columnNames.length; i++) { Object object = record.get(columnNames[i]); if (object == null) { if (keepEmptyColumn) { sb.append("\""+ columnNames[i] +"\":null,"); } } else if( object instanceof String || object instanceof Date) { sb.append("\""+ columnNames[i] +"\":\""+ object.toString() + "\","); }else if( object instanceof Integer || object instanceof Long || object instanceof Double || object instanceof BigDecimal || object instanceof Float || object instanceof Boolean) { sb.append("\""+ columnNames[i] +"\":" + object + ","); } } // 去掉最后的逗号 if (sb.charAt(sb.length()-1) == ',') { sb.deleteCharAt(sb.length()-1); } sb.append("}"); return sb.toString(); }

拼接普通的字段为json:(key:json名称,value:值,alreadyJsonKeys,是不是已经是json)

public static String concatJson(String[] keys , String[] values, String[] alreadyJsonKeys) { if (keys == null || values == null) { return null; } if (keys.length != values.length) { //throw new Exception("Json转化出错: keys 与 values 长度不相等 "); return "Json转化出错: keys 与 values 长度不相等"; } StringBuilder sb = new StringBuilder(); sb.append("{"); for (int i = 0; i < keys.length; i++) { Object object = values[i]; if (object == null) { sb.append("\""+ keys[i] +"\":null,"); }else { if(alreadyJsonKeys!= null && CollectionsUtils.indexOf(alreadyJsonKeys, keys[i])>=0 ){ sb.append("\""+ keys[i] +"\":" + object + ","); }else { sb.append("\""+ keys[i] +"\":\"" + object + "\","); } } } // 去掉最后的逗号 if (sb.charAt(sb.length()-1) == ',') { sb.deleteCharAt(sb.length()-1); } sb.append("}"); return sb.toString(); }

把一个list拼接成json

public static String concatJson(List list, boolean alreadyElementJson, boolean keepEmptyColumn) { if (list == null) { return null; } StringBuilder sb = new StringBuilder(); sb.append("["); int size = list.size(); for (int i = 0; i < size; i++) { T object = list.get(i); if (object == null) { sb.append("null"); } if (object instanceof Date) { sb.append("\"" + object + "\","); }else if(object instanceof String) { if( alreadyElementJson) { //如果已经是json字符串,则不加引号 sb.append(object.toString() + ","); }else { sb.append("\"" + object + "\","); } }else if (object instanceof Boolean){ sb.append(object.toString() + ","); } else { sb.append(objectToJson(object, keepEmptyColumn) + ","); } } // 去掉最后的逗号 if (sb.charAt(sb.length()-1) == ',') { sb.deleteCharAt(sb.length()-1); } sb.append("]"); return sb.toString(); }

public static String concatJson(List jsonObjects, boolean keepEmptyColumn) { if (jsonObjects == null) { return null; } if (jsonObjects.size() == 0) { return null; } StringBuilder sb = new StringBuilder(); sb.append("["); int size = jsonObjects.size(); for (int i = 0; i < size; i++) { sb.append(objectToJson(jsonObjects.get(i), keepEmptyColumn) + ","); } // 去掉最后的逗号 if (sb.charAt(sb.length()-1) == ',') { sb.deleteCharAt(sb.length()-1); } sb.append("]"); return sb.toString(); } //连接每个元素都已经是JSON的List public static String concatJsonStrings(List list){ if(list==null) return null; if(list.size()<=0) return "[]"; StringBuilder sb = new StringBuilder(); sb.append("["); int size = list.size(); for (int i = 0; i < size; i++) { sb.append(list.get(i) + ","); } // 去掉最后的逗号 if (sb.charAt(sb.length()-1) == ',') { sb.deleteCharAt(sb.length()-1); } sb.append("]"); return sb.toString(); }

处理集合的类:

1.通过条件筛选集合:

public static void removeByCondition(List list1, List list2, CollectionFilter filter) { for (int i = list1.size() - 1; i >= 0; i--) { T item1 = list1.get(i); for (T item2 : list2) { if (filter.same(item1, item2)) { list1.remove(i); } } } }

2.通过条件查找一个集合在另一个集合中存在的次数

public static Integer findExistCountByCondition(List list1, List list2, CollectionFilter filter) { int count = 0; for (int i = list1.size() - 1; i >= 0; i--) { T item1 = list1.get(i); for (T item2 : list2) { if (filter.same(item1, item2)) { count++; } } } return count; }

public static T findExistByCondition(List list1, List list2, CollectionFilter filter) { for (int i = list1.size() - 1; i >= 0; i--) { T item1 = list1.get(i); for (T item2 : list2) { if (filter.same(item1, item2)) { return item2; } } } return null; }

3.一个集合中根据条件合并,条件相同的只留前面的一个元素,后面的(满足条件的)元素都删除

public static void uniqueByCondition(List list, CollectionFilter filter) { for (int i = list.size() - 1; i >= 1; i--) { T item1 = list.get(i); for (int k = i - 1; k >= 0; k--) { T item2 = list.get(k); if (filter.same(item1, item2)) { list.remove(i); break; } } } }

4.一个集合中根据过滤,得到满足条件的集合

public static List filter(List list, Predicate predicate) { // list.stream().filter(predicate).collect(Collectors.toList()); //这是用stream方法 if (list == null) return null; if (predicate == null) return list; List result = new ArrayList<>(); int size = list.size(); for (int i = 0; i < size; i++) { T item1 = list.get(i); if (predicate.test(item1)) { result.add(item1); } } return result; }

一个集合中根据过滤,得到满足条件的集合的第一个元素

public static T filterFirst(List list, Predicate predicate) { // list.stream().filter(predicate).collect(Collectors.toList()); //这是用stream方法 if (list == null) return null; if (predicate == null) return null; List result = new ArrayList<>(); int size = list.size(); for (int i = 0; i < size; i++) { T item1 = list.get(i); if (predicate.test(item1)) { result.add(item1); } } if (result != null && result.size() > 0) { return result.get(0); } return null; } public static T findExsit(List list, Predicate predicate) { // list.stream().filter(predicate).collect(Collectors.toList()); //这是用stream方法 if (list == null) return null; if (predicate == null) return null; int size = list.size(); for (int i = 0; i < size; i++) { T item1 = list.get(i); if (predicate.test(item1)) { return item1; } } return null; } public static boolean findExsit(T[] arr, Predicate predicate) { // list.stream().filter(predicate).collect(Collectors.toList()); //这是用stream方法 if (arr == null) return false; if (predicate == null) return false; int size = arr.length; for (int i = 0; i < size; i++) { T item1 = arr[i]; if (predicate.test(item1)) { return true; } } return false; }

根据条件对已经排序的集合进行分组(必须排序后调用)

public static List> groupListByCategory(List allBooks, CollectionFilter filter) throws Exception { T oldRecord = null; List> allCategories = new ArrayList<>(); // 所有类的集合 List oneCategory = new ArrayList<>(); // 当前的一类 // 循环所有的对象,根据前后是否是同一类进行分类 for (T record : allBooks) { // 判断是否为新的一类 if (oldRecord == null || !filter.same(oldRecord, record)) { oneCategory = new ArrayList<>(); // 新的一类 oneCategory.add(record); allCategories.add(oneCategory); } else { oneCategory.add(record); } oldRecord = record; } return allCategories; }

对一个list集合根据条件进行分组重新构造

public static List> groupListByCondition(List> list, String itemKey, String listKey, Predicate> predicate) { List> resultMapList = new ArrayList<>(); for (Map map : list) { Map oldMap = CollectionsUtils.findExsit(resultMapList, predicate); if (oldMap != null) { List secondCategories = (List) oldMap.get(listKey); secondCategories.add(map.get(itemKey)); } else { // 如果不存在,创建一个结果集合 Object item = map.get(itemKey); map.remove(itemKey); Map map2 = new LinkedHashMap<>(); map2.putAll(map); List newList = new ArrayList<>(); newList.add(item); map2.put(listKey, newList); resultMapList.add(map2); } } return resultMapList; }

通过字段对集合中的集合进行排序 排序逻辑:外层集合的排序决定于内层集合中的第一个元素的排序

public static List> orderByFields(List> outerList, String... fields) throws Exception { // 对内层的每一个集合按照条件进行排序 for (List innerList : outerList) { innerList = sortByFields(innerList, fields); } // 外层集合进行排序: return sortByFields(outerList, fields); }

根据条件对未排序的集合进行分组

public static List> groupUnorderedListByCategory(List allRecords, CollectionFilter filter) throws Exception { List> allCategories = new ArrayList<>(); // 循环所有的对象,根据前后是否是同一类进行分类 for (T record : allRecords) { // 查看当前记录是否在原来的某一个类别中 int idx = -1; for (int i = 0; i < allCategories.size(); i++) { if (filter.same(allCategories.get(i).get(0), record)) { idx = i; break; } } // 判断是否为新的一类 if (idx < 0) { List oneCategory = new ArrayList<>(); // 新的一类 oneCategory.add(record); allCategories.add(oneCategory); } else { allCategories.get(idx).add(record);书 } } return allCategories; }

public static List sort(List allRecords, Comparator comparator) throws Exception { if (allRecords == null) return null; allRecords.sort(comparator); return allRecords; } public static T[] sort(T[] allRecords, Comparator comparator) throws Exception { if (allRecords == null) return null; Arrays.sort(allRecords, comparator); return allRecords; }

public static List sortByFields(List allRecords, String... fieldsAndAscDesc) throws Exception { if (allRecords == null) return null; if (fieldsAndAscDesc == null || fieldsAndAscDesc.length == 0) { return allRecords; // 如果不给字段参数,则不排序 } // 由于下面要从fields当中分离出(asc,desc),所以复制一份,而不要改变原参数 String[] fields = Arrays.copyOf(fieldsAndAscDesc, fieldsAndAscDesc.length); // 从fields当中取到升降要求(asc,desc) int[] ascOrDesc = new int[fields.length]; // 每个字段的升降性,1表示升,-1表示降 for (int i = 0; i < fields.length; i++) { String field = fields[i]; String[] words = field.trim().split("\\s"); if (words.length <= 1) { ascOrDesc[i] = 1; // 默认为升 } else { fields[i] = words[0]; // 剥离了asc/desc的真正字段名 if (words[1].equalsIgnoreCase("asc")) { ascOrDesc[i] = 1; } else if (words[1].equalsIgnoreCase("desc")) { ascOrDesc[i] = -1; } else { throw new Exception("asc/desc写法有误"); } } } allRecords.sort((T r1, T r2) -> { if (r1 == null && r2 == null) return 0; if (r1 == null && r2 != null) return -1; if (r1 != null && r2 == null) return 1; for (int i = 0; i < fields.length; i++) { String field = fields[i]; int ascFlg = ascOrDesc[i]; Object value1 = null; Object value2 = null; // 集合排序逻辑:外层集合的排序决定于内层集合中的第一个元素的排序 if (r1 instanceof List && r2 instanceof List) { value1 = ((List) r1).get(0).get(field); value2 = ((List) r2).get(0).get(field); } else if (r1 instanceof Record && r2 instanceof Record) { value1 = ((Record) r1).get(field); value2 = ((Record) r2).get(field); } if (value1 == null && value2 == null) continue; // 如果这个字段相等,则要循环看下一个字段 if (value1 == null && value2 != null) return -1 * ascFlg; if (value1 != null && value2 == null) return 1 * ascFlg; if (value1 instanceof Comparable) { // if(! (value2 instanceof Comparable))throw new // Exception("value2字段类型与value1不一样"); int result = ((Comparable) value1).compareTo(value2) * ascFlg; if (result != 0) return result; // 该字段能做出大小的判断。如果这个字段相等,则要循环看下一个字段 } else { // throw new Exception("字段类型不能用于比较"); //TODO 这个异常暂不处理 } } return 0; }); return allRecords; }

join两个集合

public static void join(List targetList, String[] targetFields, List fromList, String[] fromFields, String targetJoinField, String fromJoinField) throws Exception { if (targetList == null || fromList == null) { return; } if (targetFields == null || fromFields == null) { return; } if (targetFields.length != fromFields.length) { throw new Exception(" 长度不相等 "); } for (Record targetRecord : targetList) { Object joinValue = targetRecord.get(targetJoinField);// 关联的值 Record fromRecord = CollectionsUtils.filterFirst(fromList, record -> { return record.get(fromJoinField).equals(joinValue); }); if (fromRecord == null) { continue; } for (int i = 0; i < targetFields.length; i++) { String fromField = fromFields[i]; String targetField = targetFields[i]; targetRecord.set(targetField, fromRecord.get(fromField)); // 把对应的段的值取过来 } } }

public static void join(List targetList, String targetField, List fromList, String fromField, String targetJoinField, String fromJoinField) throws Exception { if (targetField == null || fromField == null) { return; } join(targetList, new String[] { targetField }, fromList, new String[] { fromField }, targetJoinField, fromJoinField); }

合并两个list,返回一个新的list

public static List union(List list1 ,List list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } List resultList = new ArrayList<>(); resultList.addAll(list1); resultList.addAll(list2); return resultList; }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:5499元起!iPhone 13,9月等你!
下一篇:Java-Iterator遍历集合
相关文章

 发表评论

暂时没有评论,来抢沙发吧~