Click here to Skip to main content
15,899,124 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been unable to get a fix for a problem . This is my problem:

long place = 2
String replaced = $field2 and $field25
afterreplacing= replaced.replace("$field" + place, '1');
When I run this it is replacing $field2 alone and also $field2 in $field25 by 1. But I want the exact word to get replaced . How can I achieve this in Java

Tested programs will be most preferred.

I tried the word boundaries but it didn't work

What I have tried:

I tried the word boundaries but it didn't work when I used $field + variable . It was getting replaced when I was using just "$field" but the purpose is not resolved.
Posted
Updated 9-Sep-16 3:56am
Comments
[no name] 9-Sep-16 9:51am    
You would have to fix the compile errors first before you could run your code.
Member 12729590 9-Sep-16 10:07am    
ThePhantomUpvoter - Focus on the logic there are no compile errors in actual.
[no name] 9-Sep-16 11:46am    
There *are* compile errors in the code that you posted that demonstrate whatever your problem is. We can't help you with your code unless you show us your code. You didn't bother to do that so we can't tell where you went wrong.

"Tested programs will be most preferred.", this is also funny in that you seem to think we are write code to order service. We are not.
Patrice T 9-Sep-16 10:20am    
Show actual code with example inputs and outputs.
Richard MacCutchan 9-Sep-16 11:16am    
"Tested programs will be most preferred."
lol.

1 solution

Use a regex: you can set it up so that it's a more sophisticated match than just "this text string": Pattern (Java Platform SE 7 )[^]

For example, the match string might be:
\$field2(?=\s|$)
Which requires the "field2" to be followed by either a space or the end of the string - so "$field25" no longer matches but the "$field2" does.
 
Share this answer
 
Comments
Member 12729590 9-Sep-16 10:05am    
but 2 is not fixed thats what
OriginalGriff 9-Sep-16 10:21am    
No, I kinda guessed that...but you are assembling your current replace string from two parts. I'm pretty sure you can work out how to assemble it from three...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900