Hi,
I'm trying to partially replace a string with a substring, like
old = "1..2..3..4"
new="1*2*3..4"
two ways to implement:
1. old.replaceAll ("\\..","*");
2. Pattern pattern = Pattern.compile("[..]{2}");
Matcher matcher = pattern.matcher(old);
matcher.replaceAll("*");
but these two result in
1*2*3*4
Can any one tell how to force to only replacing the first #1,2,
occurrances?
--
Thanks
John
Toronto
Alex Whitney - 06 Jul 2006 17:40 GMT
Split the string up using ".." as the delimeter. Insert a * between
each element. Between the nth element and n-1, insert ".." instead.
Scanner scan = new Scanner (old);
scan.useDelimiter (Pattern.compile("[..]{2}");
String newStr = "";
newStr = scan.next(); // Run time error if old is empty.
while (scan.hasNext())
{
String next = scan.next();
if (scan.hasNext())
newStr = newStr + "*" + next;
else
newStr = newStr + ".." + next;
}
> Hi,
>
[quoted text clipped - 23 lines]
> John
> Toronto
Alex Whitney - 06 Jul 2006 17:44 GMT
Oops.
Scanner scan = new Scanner (old);
scan.useDelimiter (Pattern.compile("[..]{2}");
String newStr = "";
newStr = scan.next(); // Run time error if old doesn't have enough
data...
newStr = newStr + "*" + scan.next();
newStr = newStr + "*" + scan.next();
while (scan.hasNext())
{
String next = scan.next();
if (!scan.hasNext())
newStr = newStr + ".." + next;
}
> Split the string up using ".." as the delimeter. Insert a * between
> each element. Between the nth element and n-1, insert ".." instead.
[quoted text clipped - 41 lines]
> > John
> > Toronto
Lasse Reichstein Nielsen - 06 Jul 2006 17:55 GMT
> I'm trying to partially replace a string with a substring, like
>
[quoted text clipped - 4 lines]
>
> 1. old.replaceAll ("\\..","*");
You probably also want to escape the second ".".
> 2. Pattern pattern = Pattern.compile("[..]{2}");
What are you expecting this pattern to match? It matches
exactly the same as "\\.\\." or "[.][.]".
> Can any one tell how to force to only replacing the first #1,2,
> occurrances?
1) Use String.replaceFirst twice.
2) Use split+join:
String[] parts = old.split("\\.\\.",3);
newString = parts[0] + "*" + parts[1] + "*" + parts[2];
/L

Signature
Lasse Reichstein Nielsen - lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
shakah - 06 Jul 2006 21:34 GMT
> Hi,
>
[quoted text clipped - 23 lines]
> John
> Toronto
What about a simple:
old.replaceFirst("\\.\\.", "*").replaceFirst("\\.\\.", "*") ;
?