java中的正则表达式

Python011

java中的正则表达式,第1张

Java正则表达式 (<img.*?)style=\".*?\" 替换成 $1

其中.*表示0个或0以上多个任意字符

.*?表示0个或0以上多个任意字符的非贪婪匹配,就是假如一个句子中有多个style,它匹配距离最近的那个style,同理后面的.*?匹配距离最近的双引号

$1表示反向引用,它代表的是正则表达式中的第一个小括号所括起来的分组的内容,如果有两个小括号括起来的内容,则分别用$1,$2表示它们(在替换后的字符串中)

完整的Java程序如下

123456public class CC { public static void main(String[] args) { String s="<img src=\"file/img/2016/12-28/1234-25521482893088459.jpg\" title=\"1234.jpg\" alt=\"\" width=\"396\" height=\"271\" style=\"width: 396pxheight: 271px\"/>" System.out.println(s.replaceAll("(<img.*?)style=\".*?\"", "$1"))}}

运行结果

<img src="file/img/2016/12-28/1234-25521482893088459.jpg" title="1234.jpg" alt="" width="396" height="271" />

import java.util.regex.Matcher

import java.util.regex.Pattern

public class Test6

{

public static void main(String[] args)

{

String str = "1223801,122380,14瀚华01,111"

String reg = "[^,]+,?"

Pattern p = Pattern.compile(reg)

Matcher m = p.matcher(str)

while(m.find())

{

System.out.println(m.group())

}

}

}