本人初学java,对于java正则表达式不是很理解,我想用java实现下面条件的字符串过滤,还请各位大侠帮助。
text = X+..+A + B + C +..Y,这里,text是原字符串,B是需要过滤出来的字符串,A和C是过滤B的条件,X+..和..Y是其它的干扰字符串。
本人描述可能很不清晰,举个例来说吧:String text="the background=\"yello\",good color";,这中间X+..就是the ,A是background=\", C是\",..Y是,good color ,那么需要提取的B就是yellow.
现在问题是,A的形式可以有很多种,匹配正则表达式 : "background\\s*=\\s*\"",C也匹配正则表达式"\\s*\"",那么我应该如何提取B呢?
小弟感激不尽!java正则表达式
text = X+..+A + B + C +..Y,这里,text是原字符串,B是需要过滤出来的字符串,A和C是过滤B的条件,X+..和..Y是其它的干扰字符串。
本人描述可能很不清晰,举个例来说吧:String text="the background=\"yello\",good color";,这中间X+..就是the ,A是background=\", C是\",..Y是,good color ,那么需要提取的B就是yellow.
现在问题是,A的形式可以有很多种,匹配正则表达式 : "background\\s*=\\s*\"",C也匹配正则表达式"\\s*\"",那么我应该如何提取B呢?
小弟感激不尽!java正则表达式
所以我们可以先匹配A,然后再对A后面的字串匹配C,这样就不会重合了。我写一个字串的例子,楼主找找灵感
public static void main(String[] args) {
String text = "the background=\"yello\",good color";
String A = "background=\"";
String C = "\"";
String B = getParam(text, A, C);
System.out.println("B : " + B);
}
public static String getParam(String src, String findLeft, String findRight) {
int indexFirst = -1;
int indexSecond = -1;
indexFirst = index(src, findLeft, 0);
if (indexFirst >= 0) {
indexSecond = index(src, findRight, indexFirst + findLeft.length());
if (indexSecond >= 0) {
return src.substring(indexFirst + findLeft.length(), indexSecond);
}
}
return null;
}
public static int index(String src, String obj, int indexBegin) {
int indexRet = -1;
for (int i = indexBegin, j = 0; i < src.length(); i++) {
if (src.charAt(i) == obj.charAt(0)) {
while(src.charAt(j + i) == obj.charAt(j++)) {
if (j >= obj.length()) {
indexRet = i;
break;
}
if (j + i >= src.length()) {
return -1;
}
}
}
}
return indexRet;
}
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String text = "the background=\"yello\",good color";
String[] str=text.split("\"");
System.out.println("B是:"+str[1]);
}}
我的意思是,A和C两个能不能都是正则表达式,能匹配象这样"background = "的情况,还一样可以把"yello"提取出来。
那你先匹配background和等于号,然后再匹配他后面的一对双引号就可以了。就拿你的那个text串为例,varName就是要获取的变量: String text = "the background=\"yellow\", color=\"black\" ";
String varName = "background";
Pattern pattern = Pattern.compile(varName + "\\s*=\\s*\"(.*?)\"");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String key_val = matcher.group(); // 包含变量和值的字串
String value = key_val.split("\"")[1]; // 获取双引号中的值
System.out.println(varName + " : " + value);
}
String text = "the background-image=\"a.jpg\", the color=\"black\", background-image=\"..\\common\\b.jpg\""; 我需要得到这样的字符串newText="the background-image=\"res.a.jpg\", the color=\"black\", background-image=\"res.\\common\\b.jpg\"";,即将text中所有的background-image="A(n)",中A(n),如果A(n)以".."开头就先去掉"..",然后将所有A(n)前面加上"res.",再替换掉text原A(n),返回text的值。
小弟对这种字符串替换相当的郁闷,还请大哥点拨点拨!