private static void getStrings() { String str = "zz.getSszbhgbQms()+z.getZbgjQms()+z.getJkcgQms()+z.getYygjQms()"; String str2 ; Pattern p = Pattern.compile("([a-z]+)(\\.)(get)([a-zA-Z]+)\\(\\)"); Matcher m = p.matcher(str); ArrayList<String> strs = new ArrayList<String>(); while (m.find()) { strs.add(m.group()); str = str.replace(m.group(),m.group()+"==null?0:"+m.group()); } System.out.println(str); System.out.println("getString##"); for (String s : strs){ System.out.println(s); } }
可实现功能:
将
zz.getSszbhgbQms()+z.getZbgjQms()+z.getJkcgQms()+z.getYygjQms()
转换为
zz.getSszbhgbQms()==null?0:zz.getSszbhgbQms()+z.getZbgjQms()==null?0:z.getZbgjQms()+z.getJkcgQms()==null?0:z.getJkcgQms()+z.getYygjQms()==null?0:z.getYygjQms()
为了解决get方法中有些值是null而不能相加。只能先出此下策了。
package com.iss; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Scanner的小例子,从文件中读内容 * */ public class Help{ public static void main(String[] args) throws IOException{ File file = new File("F:"+File.separator+"Work"+File.separator+"A.txt"); FileInputStream fip = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fip,"UTF-8"); BufferedReader br = new BufferedReader(isr); String temp; while((temp = br.readLine()) != null){ Pattern p = Pattern.compile("([a-z]+)(\\.)(get)([a-zA-Z]+)\\(\\)"); Matcher m = p.matcher(temp); ArrayList<String> strs = new ArrayList<String>(); while (m.find()) { strs.add(m.group()); temp = temp.replace(m.group(),m.group()+"==null?0.0:"+m.group()); } //res +=temp; System.out.println(temp); } //System.out.println(res); br.close(); isr.close(); } }原文链接:https://www.f2er.com/regex/361492.html