Search and replace strings in a file while ignoring substrings

Hi:
I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
try
          String find_productstring = "abcd";
          String replacement_productstring = "ABCDEFG";
          compsXml = new FileReader(compsLoc);
          compsConfigFile = new BufferedReader(compsXml);
          File compsFile =new File("file.xml");
          File compsNewFile =new File("file1.xml");
          BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
          while ((compsLine = compsConfigFile.readLine()) != null)
                new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                out.write(new_compsLine);
                out.write("\n");
            out.close();
            compsConfigFile.close();
            compsFile.delete();
            compsNewFile.renameTo(compsFile);
        catch (IOException e)
        //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
         try
               String find_producttopstring = "Topabcd";
               String replacement_producttopstring = "REPLACEMEFIRST";
               compsXml = new FileReader(compsLoc);
               compsConfigFile = new BufferedReader(compsXml);
               File compsFile =new File("file.xml");
               File compsNewFile =new File("file1.xml");
               BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
               while ((compsLine = compsConfigFile.readLine()) != null)
                     new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                     out.write(new_compsLine);
                     out.write("\n");
                 out.close();
                 compsConfigFile.close();
                 compsFile.delete();
                 compsNewFile.renameTo(compsFile);
             catch (IOException e)
        }Thanks a lot!

Hi:
I have a java program that searches and replaces
strings in a file. It makes a new copy of the file,
searches for a string in the copy, replaces the
string and renames the new copy to the original file,
thereafter deleting the copy.
Now searching for "abcd", for eg works fine, but
searching for "Topabcd" and replacing it doesnot work
because there is a match for "abcd" in a different
search scenario. How can I modify the code such that
if "abcd" is already searched and replaced then it
should not be searched for again or rather search for
"abcd" as entire string and not if its a substring of
another string.
In the below code output, all instances of "abcd" and
the ones of "Topabcd" are replaced by ABCDEFG and
TopABCDEF respectively, whereas according to the
desired output, "abcd" should be replaced by ABCDEFG
and "Topabcd" should be replaced by REPLACEMEFIRST.
try
String find_productstring = "abcd";
String replacement_productstring = "ABCDEFG";
compsXml = new FileReader(compsLoc);
compsConfigFile = new
BufferedReader(compsXml);
File compsFile =new File("file.xml");
File compsNewFile =new File("file1.xml");
BufferedWriter out =new BufferedWriter(new
FileWriter("file1.xml"));
while ((compsLine =
compsConfigFile.readLine()) != null)
new_compsLine
=compsLine.replaceFirst(find_productstring,
replacement_productstring);
out.write(new_compsLine);
out.write("\n");
out.close();
compsConfigFile.close();
compsFile.delete();
compsNewFile.renameTo(compsFile);
catch (IOException e)
//since "Topabcd" contains "abcd", which is
the search above and hence the string "Topabcd" is
not replaced correctly
try
               String find_producttopstring = "Topabcd";
String replacement_producttopstring =
topstring = "REPLACEMEFIRST";
               compsXml = new FileReader(compsLoc);
compsConfigFile = new
gFile = new BufferedReader(compsXml);
               File compsFile =new File("file.xml");
               File compsNewFile =new File("file1.xml");
BufferedWriter out =new BufferedWriter(new
dWriter(new FileWriter("file1.xml"));
while ((compsLine =
compsLine = compsConfigFile.readLine()) != null)
new_compsLine
new_compsLine
=compsLine.replaceFirst(find_producttopstring,
replacement_producttopstring);
out.write(new_compsLine);
out.write("\n");
out.close();
compsConfigFile.close();
compsFile.delete();
compsNewFile.renameTo(compsFile);
             catch (IOException e)
Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
while ((compsLine = compsConfigFile.readLine()) != null)
if(compsLine.matches(find_productstring))
     System.out.println("Exact match is found for abcd");
     new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
out.write(new_compsLine);
out.write("\n");
     else
     System.out.println("Exact match is not found for abcd");
     out.write(compsLine);
     out.write("\n");

Similar Messages

  • Search and Replace String throwing the wrong error message with regexp?

    This came up in a LAVA thread, and I'm not sure if there's a bug here or not. When using Search and Replace string, and using a regular expression of [(G[b|i])], LabVIEW throws error -4622, "There is an unmatched parenthesis in a regular expression."  There are obviously no unmatched parenthesis in that expression, so it seems to me that the wrong error is being thrown. I'm just not sure if that's a syntactically valid regexp. The problem seems to be with nesting [ ]'s inside ( )'s inside [ ]'s. I've tried a couple of regexp resources on the Web, and one suggests it's valid, while the other seems to think it isn't.
    Message Edited by eaolson on 03-13-2007 10:33 AM
    Attachments:
    ATML_StandardUnit2.vi ‏10 KB
    regexp.png ‏5 KB

    adambrewster wrote:
    I think your regexp is invalid.
    In regexps, brackets are not the same as parentheses.  Parens are for grouping, while brackets are for matching one of a class of characters.  Brackets can not be nested.
    If the regexp is replaced with [G[bi]], there is no error, so it's not a matter of nested brackets. I couldn't find anything on the PCRE man page that forbids nested brackets specifically, but it makes sense.
    Your expression "[(G[bi])]", therefore parses as a character class which matches '(', 'G', '[', 'b', or 'i' followed by an unmatched paren, and an unmatched bracket.
    I don't believe that's the case. Replace the regexp with [(Gbi)], and the error goes away. So it's not a matter of the '(' being literal, and then encountering a ')' without a matching '('.
    daveTW wrote:
    what string exactly you want to replace? I think the round braces are not right in this case, since they mark partial matches which are given back by "match regular expression". But you don't want to extract parts of the string, you want to replace them (or delete, with empty <replace string>). So if you leave the outer [( ... )] then your RegEx means all strings with either "Gb" or "Gi".
    It's not my regular expression. A poster at LAVA was having problems with one of his (a truly frightening one), and this seemed to be the element that was causing the problem. I'm pretty sure that the originator of the regexp meant to use G(b|i), which seems like a complicated way of matching "Gb" or "Gi", if you ask me.

  • Search and replace string function

    Hello, I am using the "search and replace string" function and it does nt seem to work consistently for me.   I am using it in a situation where I am taking an array of strings, converting this into a spreadsheet string then deleting all of the commas.  Has anyone experienced the same behavior? I have searched through other posts and found other simular faults but none of the fixes worked for this. I can post the code it needed.
    Thanks,
    Andrew

    I agree that commas are often not desirable, especially if your software should also work in countries where comma is used as a decimal seperator.
    Where are the commas coming from? Does (1) each element of the original array have one (or more), do you (2) use comma as seperator if you convert it to a spreadhseet string?
    For (1), you might just strip out the comma for each element right in the loop. For case (2) you would simply use a different separator to begin with, of course.
    Btw: you are abusing a WHILE loop as a FOR loop, because you have a fixed number of iterations. Please replace it with a FOR loop. If you use a FOR loop, LabVIEW can manage memory much more efficiently, because it can allocate the entire output array before the loop starts. For While loops, the total number of iterations is not known to the compiler. (Of course a real program would also stop the loop if an error occurs. In this case you would need to stay woth the WHILE loop. )
    Do you have a simple example how the raw array elements look like. How many commas are there?
    LabVIEW Champion . Do more with less code and in less time .

  • Search and replace string formatting

    Hi,
    I am trying to do a search and replace formatting of a string.
    In the example I am looking for string "PASSED" but it must also start with usbflash and some number + PASSED.
    I can't get the format to have a number from 1-99. The number of replacements should add up to 6 in this case. I have tried with \d for any number, and I also tried [1-99].
    Solved!
    Go to Solution.

    Right click on the Search And Replace String function.  There is an option to use Regular Expressions.  Then give this a try.
    EDIT: You will need to set the Replace All input to TRUE.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Match Pattern.png ‏12 KB

  • Search and replace string problems

    Hi to all,
    I have problem with Search and replace string function. It shows me a wrong Value (Number) from 15 to 100 is everything OK (15=0, 30=1, 45=2, 100=3), but after 100 ........
    Take look in VI and if you have any ideas post them please
    THX
    Igor 
    Attachments:
    indexing.vi ‏10 KB

    there will be no 15115 string, but 15 or 115 and 15 is 0, 115 is 4. Anyway, i have changed string input format and now its working THX for your help
    Attachments:
    indexing.vi ‏10 KB

  • Using a variable in a Powershell search and replace string

    Hi
    a couple of days ago I posted a question about doing a search and replace with wildcards
    Search and repalce with Widcards
    I got a swift and very helpful answer but now I need to build on it.
    In a text file I wanted to replace all the text between two defined words.  the script I got was this
    $text = 'Some Server this bit of text varies Language stuff'
    $text -replace '(.*Server) .+? (Language.*)','$1 it will always say this $2'
    It works great but now I want to replace "it will always say this" with a variable and I can't figure out the correct grammar to make this happen.
    Can anyone help??
    Thanks
    Alex

    Here's one way:
    $replace = 'it will aways say this'if ( $text -match '(.*Server) .+? (Language.*)' )
    { "{0} $Replace {1}" -f $matches[1,2] }
    else { $text }
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • How to get numeric result from 'search and replace' string function

    hii
    i am using search and replace function to get output.my output is of form ' *X0123.3 ' .here i am replacing the term *X01 with space because i need only 23.3 as a result.but i am unable to get that out in the output indicator.i used lot of functions like string to number and so on but i am getting output as zero .can you please suggest me wt to do.i am attaching a copy of my file.
    Attachments:
    Untitled 1.vi ‏25 KB

    Your problem is the fact that you are converting it to an integer, thus loosing the fractional part. You need to use "Fract/Exp String To Number" instead and create a DBL so yor data is 23.3 instead of 23.
    You also don't need to manipulate the string if the initial part is of constant lenght. Just use the offset input as in the figure below.
    Message Edited by altenbach on 07-31-2006 07:02 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    ToDBL.png ‏2 KB

  • How to search and replace in an xml file using java

    Hi all,
    I am new to java and Xml Programming.
    I have to search and replace a value Suresh with some other name in the below xml file.
    Any help of code in java it is of great help,and its very urgent.
    I am using java swings for generating two text boxes and a button but i am not able to search in the xml file thru the values that are entered into these text boxes.
    Thanks in advance.
    **XML File*
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <student>
    <stud_name>Suresh</stud_name>
    <stud_age>40</stud_age>
    </student>Also i am using SAX Parser in the java program
    any help of code or any tutorials for sax parisng is very urgent please help me to resolve this problem
    Edited by: Karthik84 on Aug 19, 2008 1:45 AM
    Edited by: Karthik84 on Aug 19, 2008 3:15 AM

    Using XPath to locate the elements you are after is very easy.
    Try something like this:
    import java.io.File;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    public class BasicXMLReplaceWithDOM4J {
         static String inputFile = "C:/student.xml";
         static String outputFile = "C:/studentRenamed.xml";
         public static void main(String[] args) throws Exception {
              // Read xml and build a DOM document
              Document doc = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder().parse(new InputSource(inputFile));
              // Use XPath to find all nodes where student is named 'Suresh'
              XPath xpath = XPathFactory.newInstance().newXPath();
              NodeList nodes = (NodeList)xpath
                   .evaluate("//stud_name[text()='Suresh']", doc, XPathConstants.NODESET);
              // Rename these nodes
              for (int idx = 0; idx < nodes.getLength(); idx++) {
                   nodes.item(idx).setTextContent("Suresh-Renamed");
              // Write the DOM document to the file
              Transformer xformer = TransformerFactory.newInstance().newTransformer();
              xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
    }- Roy

  • Search and replace, contents from excel file

    Hi
    I have the list in the excel file which needs to replace. The script should read the excel then replace to the opened InDesign documents.
    The excel(*.xls) file has two columns, first column has old nos. and the second column has the new numbers to replace.
    Ex:
    Column 1               Column 2
    (Search)               (Replace)
    4257/2          =>               1/2
    4257/3          =>               1/3
    4257/4          =>               1/4
    3257/2          =>               1/5
    3257/3          =>               1/6
    3257/4          =>               1/7
    4457/4          =>               2/2
    4457/5          =>               2/3
    4457/6          =>               2/4
    4457/7          =>               2/5
    Thanks in Advance,
    Thiru

    @csm_phil:
    this is a very radical method, because:
    1. you don't limit your changeGREP() to a specific table column (possibly the searched texts are found in other strings around the document and changed as well!)
    2. you are in trouble if a certain value you want to change exists more than one time (not likely, but who knows?) and you want to change it in diffrent values per instance. That will fail.
    If we deal with only ONE column of ONE table, to address issue 1 I would ask the user to select the column of the table and instead of:
    app.documents.item(0).changeGrep();
    I would use:
    app.selection[0].changeGrep();
    I don't hope issue 2 will apply in this case.
    @mr. pathi:
    However, in the case of only one column of one table to change AND if the new excel file contains ALL entries in the exact order (both all old and all new values), you could change the contents of the column by copying from excel to InDesign. No script necessary. The formatting of the old cells will be retained.
    You cannot do that by placing the new table to InDesign and copy/paste the new column to the old one, because the formatting of the copied column will be transferred as well (paste without formatting is not an option here).
    Uwe

  • Match case in search and replace string

    Hi !
    Attached, my problem.
    I am searching "toto" in input string "toto+tototi" and replace "toto" by "A0".
    I want to "match case" the search input in order to get a string result : A0+tototi
    Does it exist options allowing to match case ?
    BR,
    Vincent
    Solved!
    Go to Solution.
    Attachments:
    MatchCase.vi ‏8 KB

    Please fill all your controls with typical strings, make the new values the default, save the VI under a new name, and attach it again.
    (This allows us to quickly reproduce your problem without entering strings and having to guess what your inputs actually are)
    WIth your given string, the result seems as expected, so we need more information on what you actually want instead.
    LabVIEW Champion . Do more with less code and in less time .

  • Find and replace string in a file using batch script

    I am writing a batch script to replace " ", with " ". The below code works but it prefixes each line with the line number and :.
    It is the last part of the line that I am trying to replace.
    E.g.
    " ","BALANCE_SHEET ","ASSETS ","03","LEVEL_2 ",Asset Accounts," ",
    To be replaced as
    " ","BALANCE_SHEET ","ASSETS ","03","LEVEL_2 ",Asset Accounts," "
    Code:
    @echo off &setlocal
    set "search=" ","
    set "replace=" ""
    set "textfile=Build_Accounts_Plan_Source.txt"
    set "newfile=Build_Accounts_Plan_Source_new.txt"
    (for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
    ))>"%newfile%"
    type "%newfile%"
    Output:
    3:" ","BALANCE_SHEET ","ASSETS ","03","LEVEL_2 ",Asset Accounts," "
    Regards,
    Ragav.

    Did you retype the code or did you use copy/paste? Retyping is not a good idea.
    You can do this to find the cause of the problem:
    Run the modified code below.
    Use notepad.exe to open the file TempVBS.vbs in your %temp% folder.
    Mark & copy the code, then paste it into your reply.
    @echo off
    set "textfile=Build_Accounts_Plan_Source.txt"
    set "newfile=Build_Accounts_Plan_Source_new.txt"
    set Scr="%temp%\TempVBS.vbs"
    (  echo Set oFSO = CreateObject("Scripting.FileSystemObject"^)
       echo Set oInput = oFSO.OpenTextFile(WScript.Arguments(0^), 1^)
       echo sData = Replace(oInput.ReadAll, "," ^& VbCrLf, VbCrLf^)
       echo Set oOutput = oFSO.CreateTextFile(WScript.Arguments(1^), True^)
       echo oOutput.Write sData
       echo oInput.Close
       echo oOutput.Close) > %Scr%
    cscript //nologo %Scr% %textfile% %newfile%

  • Search and replace string not work as per required

    please find the attachment. i am trying to replace the variable names but it doesnt replace the variable as i expected. Please help me in this
    Attachments:
    Replace String.vi ‏8 KB
    Replace String.vi ‏8 KB

    You haven't configured the strings to be "default". Hence, all string elements in your attached vi's are empty.
    I have no idea what you try to achieve without those strings....
    Norbert 
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

  • Search and Replace String Function replaces line feeds when I only want spaces replaced?

    I need to replace every instance of a space or series of spaces in a multi line string with commas (or tabs) so I can dump it into a spreadsheet.
    I am using the regular expresion [\s]+ and it works but it is also replacing the end of lines (\r\n) too.
    How can I make it replace the spaces but leave teh end of lines intact?
    Solved!
    Go to Solution.
    Attachments:
    replace.vi ‏6 KB

    Right click on the search string and change it to '\' Code Display. Enter the space character (\s) correctly - you've got \\s right now.

  • Search and replace string inside a column

    Hi,
    in my table there is Column A with Type NVARCHAR.
    i need to search inside all the rows in that column to find the string "_TH" and remove it wherever it exist.
    how can i do it?

    you can follow below solution .
    Step 1: Create a temporary table to load all the records which are having column with '-TH'
    Step 2 :  Use update statement and join it with temporary table to update the qualified records
    Benefits: This is a set based solution which is optimal and high perfroming
    Script:
    create table test1(col1 nvarchar(20))
    insert into test1 values('one_th'),('two_th'),('Gauri')
    --Create Temporary table
    select * 
    into #tmp2
    from Test1
    where col1 like '%_TH%'
    --update all such rows which are having column with '_TH'
    Note: I am replacing all columns with '_TH' with space . you can replace with other characters based upon your requirement.
    update t
    set col1 = replace(t.col1,'_TH','')
    from test1 t
    inner join #tmp2 t2
    on t.col1 = t2.col1
    Please comment If this solution helps you.

  • What is the best cheap/free search and replace software for .xml files?

    Transferring my iTunes library from PC to Mac I have reached the stage where I want to edit the .xml file from PC file paths to Mac ones - which would be the best preferrably free software to do this on?

    Perhaps my comment in your other thread will help.
    tt2
    PS I don't know about the Mac, but Notepad++ will probably do your search & replace on the PC if you have to edit the XML.
    Message was edited by: turingtest2

Maybe you are looking for

  • Running a live stream from an XML playlist

    I have just successfully installed Adobe FMS on my server. I would now like to know how to program a script to run a continuous live stream, of MP4 videos, from an XML playlist. Can anyone tell me how to do this? ...or provide me a good tutorial? (I

  • Font not displaying properly

    Recently did a clean install of Windows 7. Installed Firefox, and text on webpages looks horrible. Here is a screenshot http://i.imgur.com/U5R84Bc.png I tried disabling hardware acceleration, no effect. I reinstalled the Arial font, which the web ins

  • Creation of Vehicle in VMS

    Hi, Pls advise the vehilce creation process in VMS. Regards, Student

  • Intel MicroLAN

    In Gary W. Johnson's book, "LabVIEW Graphical Programming", 2nd Edition, 1997, on page 246 he discusses the "Intel MicroLAN 9-bit protocol RS-485 multidrop system". He says, "A few instruments" use this protocol. At my previous employment I became an

  • SWCV PROBLEM

    HI EVERYONE I MADE AN EXPORT/IMPORT OF A NAMESPACE FROM QAS TO DEV. WITH THAT I CORRECTED SOME INCOSCISTENCES. BUT NOW I CAN NOT CHANGE ANYTHING, IT SAYS:  "SOFTWARE COMPONENT VERSION CANNOT BE CHANGED". CAN SOMEONE HELP ME TO SOLVE IT OR TELL ME HOW