0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaの正規表現でマッチ箇所に応じた値で置換する

Posted at

たとえば、以下のようなSQL文字列のバインドパラメータを実際の値で置き換えることを考える。

insert into table1(c1, c2, c3) values (?, ?, ?)
insert into table1(c1, c2, c3) values (1, 2, 3)
String[] v = {"1", "2", "3"};
		
Pattern p = Pattern.compile("\\?");
Matcher m = p.matcher("insert into table1(c1, c2, c3) values (?, ?, ?)");
		
StringBuffer sb = new StringBuffer();
for (int i=0; m.find(); i++) {
	m.appendReplacement(sb, v[i]);
}
m.appendTail(sb);
System.out.println(sb.toString());
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?