要求:
1.--test说明 能输出--test说明
2.东奔西走--test 能输出--test
3."--serwef" 不用输出
4.'--serwef' 不用输出
4."--sdfas" --etaetta 能输出--etaetta
5."aerewrfa "--test 能输出--test
6."jsdfsd--sdfsdf" --test 能输出--test
7."jsdfsd--sdfsdf" --test's 能输出--test's
8."jsdfsd--sdfsdf" --test"s" 能输出--test"s"
9.--"这也是能输出的"呀 能输出--"这也是能输出的"呀
private String getMemo(String str){
str ="--test说明,东奔西走--test,\"--serwef\",'--serwef'" +
",\"--sdfas\" --etaetta,\"aerewrfa \"--test,\"jsdfsd--sdfsdf\" --test,\"jsdfsd--sdfsdf\" --test's,\"jsdfsd--sdfsdf\" --test\"s\"";
String[] strArr = str.split(",");
String memo ="";
for (int i =0;i<strArr.length;i++){
Pattern p = Pattern.compile("--[^\"\']*$");
Matcher m = p.matcher(strArr[i]);
while (m.find()){
memo = m.group();
}
}
return memo;
}
昨天提问过,后来发现那个表达式不能匹配7,8,9的情况.望指教
正则也是可以的
[code="java"]
private final static Pattern pattern =
Pattern.compile("^(?:(?:\"[^\"]*\"|'[^']*'|[^'\"\r\n])*)(--.*)$");
private static String getMemo(String string) {
Matcher m = pattern.matcher(string);
return (m.matches()) ? m.group(1) : null;
}
[/code]
没看明白~~
别用正则表达式了,JDK自带的正则表达式功能不是很完备,还是自己额外写一个解析的方法吧。
根据你的规则,去解析字符串。
比如:
首先,找到一个双引号(或者单引号),然后找下一个与之匹配的双引号(或者单引号),如果中间含有--,这不输出
等等。。。
要根据你的规则来定。
[code="java"]
// 规则: 找到最后一个 --, 再判断前面的引号匹配是否正确,
// 正确就说明最后一个--表达式是所求的
private String getMemo(String string) {
int index = string.lastIndexOf("--");
if (index != -1) {
for (int i = 0; i < index; i++) {
char ch = string.charAt(i);
if (ch == '"' || ch == '\'') {
for (i++; (i < index) && (string.charAt(i) != ch); i++) {
; // NULL
}
if (i == index) {
return null;
}
}
}
return string.substring(index);
}
return null;
}
[/code]