File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes matching a string in a line Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "matching a string in a line " Watch "matching a string in a line " New topic

matching a string in a line

Raj kalaria
Ranch Hand

Joined: Sep 08, 2005
Posts: 72

I am trying to read a file and looking for a specific word "drugs" in a line and trying to replace the word by "medicine"
try {
BufferedReader in = new BufferedReader(new FileReader(objTemplateFile));
String str;
while ((str = in.readLine()) != null)
if (str.matches("DQLString"))
System.out.println("we have a match");
} catch (IOException e) {}

but i think so "str.matches" matched the entire line and not a word in the line. Can some one tell how to find a word in a line and replace that word with a new word.

Any help would be appreciated

marc weber

Joined: Aug 31, 2004
Posts: 11343

Have you looked at the various "replace" methods in String?

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Raj kalaria
Ranch Hand

Joined: Sep 08, 2005
Posts: 72
public final class tm {
private static String REGEX = "upper('%test%')))";

private static String INPUT = "DQLString=SELECT object_name,r_creation_date FROM library_object WHERE (((upper(library_type) = upper('Posters')) and (upper(product_name) like upper('%test%')))"
private static String REPLACE = "CIPLA";

public static void main(String[] argv) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
INPUT = m.replaceAll(REPLACE);


can some oneplease helpwhy my string is not being replaced ( I am trying to replace upper('%test%'))) with Cipla

it throws mw the error
Unmatched closing ')' near index 14
I agree. Here's the link:
subject: matching a string in a line
It's not a secret anymore!