Reg Ex Question

S

sks

I'm having trouble working out how to use a reg ex to replace certain
characters inside a string which contains some html.

String string = "<table>zmzmz<tr><td>Hello</td></tr></table>";

I want to replace the z's inside the <table> and <tr> tags with y's to get

<table>ymymy<tr>.... etc.

I can create my pattern,

Pattern pattern = Pattern.compile("<table>[(.*?z.*?)]{0,}<tr>");

get my matcher, but there doesn't seem to be a replace(int group, String
replacement) method or similar. Anyone help ?
 
A

Ann

sks said:
I'm having trouble working out how to use a reg ex to replace certain
characters inside a string which contains some html.

String string = "<table>zmzmz<tr><td>Hello</td></tr></table>";

I want to replace the z's inside the <table> and <tr> tags with y's to get

<table>ymymy<tr>.... etc.

This is not valid html is it?
 
A

anonymous

sks said:
I'm having trouble working out how to use a reg ex to replace certain
characters inside a string which contains some html.

String string = "<table>zmzmz<tr><td>Hello</td></tr></table>";

I want to replace the z's inside the <table> and <tr> tags with y's to get

<table>ymymy<tr>.... etc.

I can create my pattern,

Pattern pattern = Pattern.compile("<table>[(.*?z.*?)]{0,}<tr>");

get my matcher, but there doesn't seem to be a replace(int group, String
replacement) method or similar. Anyone help ?
Well, String.replaceAll(String, String) takes a regex as its first
argument, so if you can create the pattern, it should be simple.
 
A

Alan Moore

This is a two-level operation: locate the range of text you want to
work in with one regex, then use a different regex to do a replacement.
The regex API doesn't provide such a facility, but you can roll your
own. Here's one way:

//==== code ========================================================

import java.util.regex.*;

class Test
{
public static void main(String[] args)
{
String input = "<table>zmzmz<tr><td>Hello</td></tr></table>";

Pattern p = Pattern.compile("(?<=<table>)[^<]+(?=<tr>)");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find())
{
m.appendReplacement(sb, "");
sb.append(m.group().replaceAll("z", "y"));
}
m.appendTail(sb);

System.out.println(sb.toString());
}
}

//==================================================================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top