比如:
有个字符串为 abcdef[wx]hijk<i>aaa</i>lmn[fn]opq<i>bbbb</i>rst
我现在要得到 [wx]、<i>aaa</i>、[fn]、<i>bbbb</i> 这四个值及他们的索引,怎么实现?
望大家帮帮忙...
------解决方案--------------------------------------------------------
String str ="abcdef[wx]hijk<i>aaa</i>lmn[fn]opq<i>bbbb</i>rst"
int newStr = str.indexof("[wx]");
其他同上!
------解决方案--------------------------------------------------------
正则表达式
------解决方案--------------------------------------------------------
- Java code
(\[\w+\])|(\<i\>\w+\<\/i\>)
------解决方案--------------------------------------------------------
- Java code
String s = "abcdef[wx]hijk<i>aaa</i>lmn[fn]opq<i>bbbb</i>rst"; String px = "[a-z]*(\\[[a-z]*\\])[a-z]*(<i>[a-z]*</i>)"; Pattern p = Pattern.compile(px); Matcher m = p.matcher(s); while (m.find()) { System.out.println(m.group(1)); System.out.println(m.group(2)); }
------解决方案--------------------------------------------------------
- Java code
String scontent="abcdef[wx]hijk<i>aaa</i>lmn[fn]opq<i>bbbb</i>rst"; String rex = "(\\[\\w+\\])|(\\<i\\>\\w+\\<\\/i\\>)"; Pattern p = Pattern.compile(rex); Matcher m = p.matcher(scontent); while(m.find()){ System.out.println(m.group()); }
------解决方案--------------------------------------------------------
System.out.println(m.group()+m.start());起始值索引
------解决方案--------------------------------------------------------
for example
- Java code
String s = "abcdef[wx]hijk<i>aaa</i>lmn[fn]opq<i>bbbb</i>rst";Pattern p = Pattern.compile("\\[\\w+\\]|(?i)<i\\s*>.*?</i>");Matcher m = p.matcher(s);while (m.find()) { System.out.println(m.group());}
------解决方案--------------------------------------------------------
- Java code
String s = "abcdef[wx]hijk<i>aaa</i>lmn[fn]opq<i>bbbb</i>rst"; Pattern p = Pattern.compile("\\[\\w+\\]|(<i>\\w+</i>)"); Matcher m = p.matcher(s); while(m.find()) { System.err.println("index = " + m.start() + ", string = " + m.group()); }
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
- Java code
String str="abcdef[wx]hijk<i>aaa</i>lmn[fn]opq<i>bbbb</i>rst"; Pattern pat=Pattern.compile("(?:\\[.*?\\]|<(.*?)>[^<]+</\\1>)"); Matcher mcr=pat.matcher(str); while(mcr.find()){ System.out.println(mcr.start()+" "+mcr.group()+" "+mcr.end()); }