怎么用java正则去匹配I am name,name是一个参数,再把name替换成一个指定的值
如: it is a test, THIS IS Alink..
我要修改test,link的值,修改成 test1,link1.
最终效果是 it is a test1,THIS IS A link1..
类似这样……么?
[code="java"]import java.util.*;
import java.util.regex.*;
public class Demo {
public static void main(String[] args) {
String src = "it is a test, THIS IS A link..";
String expected = "it is a test1, THIS IS A link1..";
Map<String, String> map = new HashMap<String, String>();
map.put("test", "test1");
map.put("link", "link1");
String regex = "(<BUTTON\\s+name=)(.+?)(\\s*>)\\2</BUTTON>";
Matcher m = Pattern.compile(regex).matcher(src);
StringBuffer buf = new StringBuffer();
while (m.find()) {
String key = m.group(2);
String value = map.get(key);
if (null != value) {
m.appendReplacement(buf, "$1" + value + "$3" + value + "</BUTTON>");
} else {
m.appendReplacement(buf, "$0");
}
}
m.appendTail(buf);
String result = buf.toString();
System.out.println(expected.equals(result));
}
}[/code]
最后是弄个占位符,如果$name$。如果第一次又要静态的,那就比较麻烦了
可以用javascript啊,好像很容易做到的
说得这么含糊,都不知道怎样帮你,等一下,我随便写个给你
[code="java"]
public static void main(String[] args) {
String src = "it is a test1,THIS IS A link1...";
String label = "BUTTON";
String attr = "id";
//分步,先把标签匹配好,再对每个标签操作
String regx = "<" + label + "[\\w= ]+> *\\w+ *</+" + label + ">";
Pattern p = Pattern.compile(regx);
Matcher m = p.matcher(src);
while(m.find()){
//找到的每个匹配的标签
String temp = m.group();
//然后把你想要的再找出来,自己参考Matcher和Pattern类
.....
}
}
[/code]
getElementById("name").value=XX...