如何得到两个双括号里面内容,由于一个字符串中可能有多组双括号,所以不好用substring.indexOf("{{")...求助
String str="my name is {{ name }},my email is {{ email }},my school is {{ xxx }}"; //如何得到多组花括号中内容(name,email,xxx)?分割之类的都不好分?
public static void main(String[] args) { ArrayList<String> keys = new ArrayList<String>(); String str = "my name is {{ name }},my email is {{ email }},my school is {{ xxx }}"; Pattern p = Pattern.compile("\\{\\{\\s*(\\w*)\\s*\\}\\}"); Matcher m = p.matcher(str); while (m.find()) { keys.add(m.group(1)); } System.out.println(keys); }
https://msdn.microsoft.com/zh-cn/library/aa989779(v=vs.80).aspx
善用indexOf的第二个参数,没事多看msdn。
String str="my name is {{ name }},my email is {{ email }},my school is {{ xxx }}"; int index=0; for(int i=0;i<str.length();i++ { int index1 = str.indexOf("{{ ",index); if (index1==-1) break; int index2 = str.indexOf(" }}",index1+3); if (index2==-1) break; index=index2+3; string fragment=str.substring(index1+3,index2); // fragment分别是"name", "email", "xxx" }
1.手动分割
2.正则表达式
推荐正则
用正则表达式吧,如下:
public static void main(String[] args) { String str="my name is {{ name }},my email is {{ email }},my school is {{ xxx }}"; Pattern pattern = Pattern.compile("\\{\\{([^\\}]+)\\}\\}"); Matcher matcher = pattern.matcher(str); while(matcher.find()){ String t = matcher.group(1); System.out.println(t); } }