Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replacing Values with other values

Status
Not open for further replies.

sjohri214

Programmer
Jul 19, 2002
24
0
0
GB
Hi,

I hope someone can help me with the follwing problem?
it's a bit tricky to explain but ...

I have a file with the following data contained within it:

1 ODH_ARTSP,
2 DHLO_AGRVI,
3 ILV5_SPIOL,
4 MMSB_PSEAE,
5 6PGD_SHEEP
;
tree PAUP_1 = [&U] (1,(2,((3,5),4)));


Does anyone know how i can replace the digits in the the part of the file i.e. (1,(2,((3,5),4)));
with the corresponding text above it.
In order that i can end up with the following result:

(ODH_ARTSP,(DHLO_AGRVI,((ILV5_SPIOL,6PGD_SHEEP),MMSB_PSEAE)));

I have tried doing this replacement using Regular Expressions, but because I replace one by one it replaces the numbers in the replacement text as well so, ILV5_SPIOL becomes ILV6PGD_SHEEP_SPIOL because 6PGD_SHEEP is supposed to replace 5.

Does anyone have any idea of how i can go about doing this?

Any kind of help would be much appreciated

Thanks again
 
Use:
Code:
String str = "(1,(2,((3,5),4)))";
str.replaceAll("5","6PGD_SHEEP");
Or if you don't want to mess with other numbers containing 5 (like 25):
Code:
String str = "(1,(2,((3,5),4)))";
str.replaceAll("\\D5\\D","6PGD_SHEEP");
In java regex '\D' means non-digit, and '\\D' means place '\' into the string literal followed by 'D'.
 
Oops. The second of bit of code is incorrect, as replacing '\D5\D' with the value would elminate the two non-digits. Also, a 5 at the beginning or end of a string would be ignored. (It still feels like a Monday...)
To do this matching correctly, you can use the
Code:
java.util.regex
package:
(See for java regex info)
Code:
String sNum = "5";
String sVal = "6PGD_SHEEP";
// add spaces to match digits at front and back
str = " "+str+" ";
// replace pattern
// \D5\D
String sRegex = "(\\D)"+sNum+"(\\D)";
// string to replace with
// $1 and $2 mean the values of group 1 and 2 - (\\D)
// these are added back to the replace string
String sRep = "$1"+sVal+"$2";
str.replaceAll(sRegex,sRep);
// trim the extra spaces
str = str.trim();
You can also use the regex package directly.
 
Hi HavaTheJut,

Thanks very much for the help, i was trying to find a way of referencing the captured groups using the m.group method, and didn't realise u could use the $1 method - (i thought this was restricted to Perl!)

Thanks again for your help
Much appreciated!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top