Multiple replacements from an input file with 1.4 Regex

hi,
i'm trying to make multiple replacments to a source file <source> using a second input file <patterns> to hold the regex's. the problem i'm having is that the output file only makes the last replacement listed in the input file. Example if the input file is
a#123
b#456
only b is changed to 456 and a remains.
the second debug i've got shows that all the replacements are in memory, but i'm not sure how to write them all to the file.
the syntax is Java MyPatternMatcher <source> <patterns>
import java.util.regex.*;
import java.io.*;
import java.util.*;
public class MyPatternResolver {
     private File patternFile;
     private File sourceFile;
     private Vector patterns = new Vector();
     public MyPatternResolver(String sourceFile, String patternFile) {
          this.sourceFile = new File(sourceFile);
          this.patternFile = new File(patternFile);
          loadPatterns();
          resolve();
     private void loadPatterns() {
          // read in each line if File
          FileReader fileReader = null;
          try {
               fileReader = new FileReader(patternFile);
          } catch(FileNotFoundException fnfe) {
               fnfe.printStackTrace();
          BufferedReader reader = new BufferedReader(fileReader);
          String s = null;
          String[] strArr = new String[2];
          try {
               while((s = reader.readLine()) != null) {
                    StringTokenizer tokenizer = new StringTokenizer(s, "#");
                    for (int i =0; i < 2; i++) {
                         strArr[i] = tokenizer.nextToken();
                         //Debugging Info
                         System.out.println("Token Value " + i + " = " + strArr);
                         //End Debugging Info
                    patterns.add(new PatternResolver(strArr[0], strArr[1], sourceFile));
          } catch(IOException ioe) {
                    ioe.printStackTrace();
     private void resolve() {
          Iterator iterator = patterns.iterator();
          while(iterator.hasNext()) {
               PatternResolver pr = (PatternResolver) iterator.next();
               pr.resolve();
     public static void main(String[] args) {
          MyPatternResolver mpr = new MyPatternResolver(args[0], args[1]);
     public class PatternResolver {
          private String match, replace;
          private File source;
     public PatternResolver(String s1, String s2, File f) {
          this.match = s1;
          this.replace = s2;
          this.source = f;
     public File resolve() {
          File fout = null;
          try {
     //Create a file object with the file name in the argument:
     fout = new File(sourceFile.getName() + "_");
     //Open and input and output stream
     FileInputStream fis = new FileInputStream(sourceFile);
     FileOutputStream fos = new FileOutputStream(fout);
     BufferedReader in = new BufferedReader(new InputStreamReader(fis));
     BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
     // The find and replace statements
     Pattern p = Pattern.compile(match);
               Matcher m = p.matcher(replace);
               //Debugging Info
               System.out.println("Match value = " + match + " Replace value = " + replace);
               //Debugging Complete
               String aLine = null;
               while((aLine = in.readLine()) != null) {
               m.reset(aLine);
               //Make replacements
               String result = m.replaceAll(replace);
               out.write(result);
          out.newLine();
               in.close();
               out.close();
          } catch (Exception e) {
               e.printStackTrace();
return fout;

If your aim is to learn about regex, then its okay.
Otherwise you might want to check the utility "sed" (stream editor) which does something similar what you are up to. It is a POSIX (.i.e. UNIX) utility, but it is available (in several versions) for other platforms (including Windows) too. (Cf. Cygnus or Mingw).

Similar Messages

  • Create two identical idocs from one input file with BPM

    Hello all .
    My issue is the following.
    I have a scenario where an input file is mapped to an IDOC .
    The problem is that i need to create a second - almost identical - mapping to the same IDOC type and when the input file is receive both of them should be sent .
    I suppose that BPM is needed for this scenario, but are there any examples or tips i should follow?
    Thank you all in advance .

    Rucinski and Sarvesh, thank you both for your answers , they are very helpful.
    I have started trying Rucinski's method, because I would better avoid redoing the mapping on the second IDOC (it is pretty hard and critical) . But I have a problem.
    When i run the senario, the system replies (for the second IDOC)
    "Unable to interpret IDoc interface NEW_IDOC_MI"
    The reason for this is that in the Interface Determination i have two entries for the inbound interface,
    Orders.orders05 and
    NEW_IDOC_MI,
    which is wrong. I should be using the original  Orders.orders05. But this can't be done, because in tha case the Interface Determination, requests a Condition to be entered. Any suggestions on this ?
    Sarvesh, is there any way to duplicate the IDOC, keeping the mapping that is allready done ?

  • I am trying to create a print ready PDF from a word file with unacceptable results.

    I am trying to create a print ready PDF from a word file with unacceptable results.
    The word file has a trim size of 6” x 9”. It has been set to mirror margins with the inner, top and bottom margins set to 0.75”, the outer margin is set to 0.5” and the gutter to 0.14”.
    It doesn’t matter if I create the PDF from inside Word, or open Acrobat Pro 11.0.9 and click Create From File, while the resulting document size is correct and the odd numbered pages reflect the correct margins, the even numbered pages do not. This results in some text near the outer margin, as well as the page numbers being omitted.
    Does anyone know how to correct this?
    I just noticed that some of the odd numbered pages' text is also cropped. Apparently Acrobat is refusing to set side margins to smaller than 1" (@ 3cm).

    I'm away from my printer, so I'll try it later. Even so, the proposed test is irrelevant. I operate a small publishing house and am trying to upload certain novels to Ingram, the largest book distributor in the world. The specifications I've set are the specifications they've asked for. Since they've said that the results I'm obtaining are unacceptable, and since they demand submission in PDF form, this renders Acrobat Pro for Mac completely unacceptable for anyone in the publication industry. As far as I can tell, Adobe has a serious bug here that it needs to fix—and at once.

  • How to print an excel file (2010 version) with multiple tabs into a pdf file with bookmarks (acrobat 9). I was able to do this easily using excel (2007 version).

    Recently I got a new laptop, with excel 2010 version and acrobat 9 standard.
    I could no longer print (save as) an excel file with multiple tabs into a pdf file with bookmarks.
    My old computer has excel 2007 version and acrobat 9 standard.
    Print an excel file into pdf with bookmarks was a piece of cake.
    Both machine has the same add-in -- Acrobat PDFMaker Office COM addin
    Thanks if anyone could help me with this.
        Tom

    You need to upgrade Acrobat to a newer version.
    On Thu, Oct 30, 2014 at 4:12 PM, excel-pdf-bookmarks <

  • I can't use thunderbird 31.2.0 to send attachement from a pdf file with Acrobat PRO XI

    I can't use thunderbird 31.2.0 (Mozilla) to send attachement from a pdf file with Acrobat PRO XI. Each time, Acrobat replies (in french) : "il n'y a pas de client pour la messagerie par défaut". Thunderbird is indicated as "by default" in the list of programs of Windows.
    Even if I type my e-mail address, etc. in the account of Acrobat, it doesn't change. Each time, I have to record a PDF file in a folder and return to Thunderbird to send it as attached. It is a too long process,  compared with Windows XP with Acrobat Reader or Acrobat 5, I had before.
    Would you please help me to explain the process. My OS is Windows 8.1.
    Thank you

    Thank you for your answer.
    What i want to do : to send PDF files as attached documents in a message
    generated by thunderbird by my e-mail address [email protected] or
    another one I have.
    When I introduce my e-mail address under Edit-Preferences-Email
    Accounts, Acrobat ask the e-mail account, the password, the IMAP for
    ingoing message (and I use POP) and SMTP for outgoing messages. Even I
    introduce all the datas, it doesn't change, Acrobat is unable to send
    the message. And the process is not convenient, because I need all my
    outgoing messages be documented inside Thunderbird.
    So, I repeat my request : how can I use thenderbird as program by
    default from Acrobat or any other software ?
    Thank you for your next message.
    Jean-Luc Rongé
    Le 21-10-14 14:24, ANAND8502 a écrit :
    >
          I can't use thunderbird 31.2.0 to send attachement from a pdf
          file with Acrobat PRO XI
    created by ANAND8502 <https://forums.adobe.com/people/ANAND8502> in
    /Acrobat Installation & Update Issues/ - View the full discussion
    <https://forums.adobe.com/message/6850947#6850947>

  • How can i make a picture from a video file with final cut pro x?

    how can i make a picture from a video file with final cut pro x?

    Go to the "share" menu, select "save current frame"

  • Return multiple columns from an analytic function with a window

    Hello,
    Is it possible to obtain multiple columns from an analytic function with a window?
    I have a table with 4 columns, an id, a test id, a date, and the result of a test. I'm using an analytic function to obtain, for each row, the current test value, and the maximum test value in the next 2 days like so:
    select
    id,
    test_id,
    date,
    result,
    MAX ( result ) over ( partition BY id, test_id order by date RANGE BETWEEN CURRENT ROW AND INTERVAL '2' DAY FOLLOWING ) AS max_result_next_two_day
    from table
    This is working fine, but I would like to also obtain the date when the max result occurs. I can see that this would be possible using a self join, but I'd like to know if there is a better way? I cannot use the FIRST_VALUE aggregate function and order by result, because the window function needs to be ordered by the date.
    It would be a great help if you could provide any pointers/suggestions.
    Thanks,
    Dan
    http://danieljamesscott.org

    Assuming RESULT is a positive integer that has a maximum width of, say 10,
    and assuming date has no time-component:
    select
       id
      ,test_id
      ,date
      ,result
      ,to_number(substr(max_result_with_date,1,10)) as max_result_next_two_day
      ,to_date(substr(max_result_with_date,11),'YYYYMMDD') as date_where_max_result_occurs
    from (select
            id
           ,test_id
           ,date
           ,result
           ,MAX(lpad(to_char(result),10,'0')||to_char(date,'YYYYMMDD'))
               over (partition BY id, test_id
                     order by date
                     RANGE BETWEEN CURRENT ROW AND INTERVAL '2' DAY FOLLOWING )
            AS max_result_with_date
          from table)

  • Having trouble with reading hex from an input file - please help

    Hi, I have a txt file with rows of hex, and I need to read each line and add it to an int array. So far I have:
    BufferedReader fileIn = new BufferedReader(new FileReader("memory.txt"));
                    int count = 0 ;
                    String temp = fileIn.readLine();
                    int file_in = Integer.parseInt(temp) ;
                    while(temp!=null) {
                         data[count] = file_in;
                         temp = fileIn.readLine();
                         file_in = Integer.parseInt(temp,16);// Integer.parseInt() ;
                         count++ ; /* increment counter */
                    } memory.txt:
    4004000
    4008000
    3FDF4018
    4108200
    3C104001
    FFFFFFE8
    4010C6C0
    FFFFFFE8
    94000000The above code crashes on the third input (my guess is becuase there are letters in and it can't parseInt letters.
    I think I need to parse it into an array of chars instead, however I don't know how to get from the string (temp) to the char array.
    can anyone help?

    ok turns out it's just a null pointer exception on the data[count] line, becuase I've only initialised the first two slots of data. i didn't see it before becase it was just throwing an error and i never printed it out.
    here's how I've defined data:
    in the class
    int[] data;just before the code to input the file data:
    for ( int i = 0; i < length; i++ )       
                    data [ i ] = 0;thinking this shoudl go through all the array and initialise it. but it gives a NullPointerException on the data=0; line.
    any ideas?
    Edited by: rudeboymcc on Feb 6, 2008 10:50 PM
    Edited by: rudeboymcc on Feb 6, 2008 10:51 PM

  • Reading each value from spreadshee​t file with delay (multiple rows and columns)

    Hi,
    a) I want to read EACH VALUE from a spreadsheet file having multiple rows and columns WITH DELAY. I am attaching my VI and sample datalog file for reference (tempsensor.txt).I need to do so because as soon as I read put ON the Sensor button on front panel, LV reads all the values at one go. I need the values for each temperature to be displayed after a delay.
    b) Secondly, I would like to read another file containing the state of four antennas (deployed:1; undeployed:0). I am logging state of each antenna in each column of the file(magnet.txt) I need to have four LEDS on front panel to display state of the antennas. I dont know what I have done for antennas in my VI is right or wrong. I guess thats rhe wrong way to approach the problem. Please help!!!(column1: Antenna1 state ; Column2:Antenna2 state.. and so..on..)
    Any help would be greatly appreciated!!
    Thanks in advance,
    Ratnesh
    FYI: The first column in my datalog file represents timestamp(number of seconds elapsed), second column: reading for temperature sensor 1, third column: reading for temperature senosr 2, and so on. I am using approx. 11 temperature sensors.
    Also, I have generated the log files for the reference purpose only. They do not represent the actual values. They are far away from actual values.
    Attachments:
    01032005.zip ‏30 KB

    Look at this modified version of your VI. After looking at it, I determined that a shift reggister was not required in this case.
    Lynn
    Attachments:
    MultiSensors.2.vi ‏85 KB

  • Reading dilimited input from a text file with tokenizer

    i am trying to read in a text file with the following structure: 2 integers on each line with comma as the delimitor.
    i am using the BufferedReader stream and Tokenizer to detect ",".
    try {
    BufferedReader in = new BufferedReader(new FileReader(filename));
    //read in the data file
    while ((s = in.readLine())!= null) {
    int i = 0;
    for (i = 0; i < 100; i++) {
    t = new StringTokenizer(s,",");
    A1 = Integer.parseInt(t.nextToken());
    catch (IOException e) {System.err.println(e);}
    When i print out A1[i], it only reads the last line of the text file. Please tell me what's wrong.
    Also i'd really like A1[i] to store the integer before the comma and another array A2[i] to store the integer after the comma. Please help.
    Thanks.
    p.s. A1 and A2 are arrays...when i previewd message in Netscape 7 it left out the brackets and the index....

    What is the for i loop for? If it is to read the next line from the file, then the while loop has taken care of it. Other than this there should be no problem with the rest of the code.
    Just add another line to store the next token into A2.

  • How to populate a form from an xml file with multiple records

    I want to be able to create a single form that will add pages as needed based upon the number of records being imported from an xml file.
    I have an IRS form that does this exactly, but I do not know how to re-create it.  I entered data into the form, then exported that data to xml.  Then I opened that xml file in excel and added more records (this is just an easy way to manage the xml data in a tabular form).  Then I import the changed xml file into the IRS form and it adds as many pages as I have records.  Perfect!  Unfortunately, I cannot edit the form to examine the technique.  It does not appear to be relying upon any additional local javascript files.  It does use an 'add page' button which may suggest the form is using the template .spawn() technique, but when I try that in my own form, it gives me unique field names for each page which are then not consistent with the xml data.  Hopefully someone can help me understand what I am missing.

    did you want
    <record>0
    <data>"11.97.23.174/32"
    <record>address <data>
    <record>address <data>
    <record>subnet <data>
    <record>ip <data>"10.97.23.174"</data></record>
    </data></record>
    </data></record>
    </data></record>
    </data></record>
    or
    <record>0
    <data>"11.97.23.174/32"
    <record>address <data>
    <record>address <data>
    <record>subnet <data>
    <record>ip <data>"10.97.23.174"</data></record>

  • Extracting body with header and trailer multiple times from a multirow file

    Hello Everyone,
    I am new to OSB and currently working on a project where I need to extract data from a flat file containing multiple rows of body and a single header and trailer in the following fashion:
    Original File:
    <Header></Header>
    <Details></Details>
    <Details></Details>
    <Trailer></Trailer>
    Desired format using OSB:
    <Header></Header>
    <Details></Details>
    <Trailer></Trailer> ... in a single file, multiple times
    Please help me in carrying out this functionality. It's really urgent and important.
    Thanks,
    Saurabh

    Some may argue this is not the right forum - database general might have been a little been than downloads - but now the thread is here I'll try an answer.
    As I see it It depends on your spooling tool.
    Lets assume you are using sqlplus.
    I that case the sql prompt command may serve your purpose
    Alternatively
    select 'header' from dual
    union all
    select field1||','||field2||','field3 .... /*must single string expression but may concatentate field */ from somtable
    union all
    select 'trailer' from dual;may suit.
    However I fear either I have not understood the question or if I have understood the question that you may have difficulties implementing this.
    Edited by: bigdelboy on 19-Apr-2009 14:32

  • How do i use an input file with Asian characters(Unicode)?

    /* Ardor
    * Illiteraminator.java
    * Version beta 1.0
    * December 7, 2007
    * Main interfacing class
    import java.io.*;
    import java.util.*;
    public class Illiteraminator{
      public static void main (String [] args){
      //  ArrayList<Word> dictionary = new ArrayList<Word>();
        String fileName = "Mandrin.txt";
        String character= "",definition = "",inputLine;
        try{
          Scanner fileScan = new Scanner (new File (fileName));
          while (fileScan.hasNext()){
            inputLine = fileScan.nextLine();
            Scanner sc = new Scanner(inputLine);
            character = sc.next();
            while (sc.hasNext()){
              definition = definition + " " + sc.next();
            }//end while sc
           // dictionary.add(new Word(character, definition));
            //definition = "";
            //character = "";
          }//end while fileScan
        } catch (FileNotFoundException e){
          System.out.println("File not found, dig around for Mandrin.txt");
          System.exit(1);
        }//end catch
        System.out.println(character);
        System.out.println(definition);
      }//end main
    }//end class IlliteraminatorHi, i'm a first time programmer. Never touched programming until i took a Java class in university last semester. I am currently attempting to write a program to help me move away from my illiteracy in Mandrin. So, that's my code, and i am using Dr.Java while writing it. When i tested it out the output looked something like this v
    A p p l e
    M o n k e y C a t D o n k e y
    My input file is saved in Unicode. It contains letters that cannot be saved in ANSI. I tried UTF-8, but the interactions section showed no output...
    Is this just a problem with Dr.Java? Will i encounter a similar problem when i turn this into a GUI?
    The following is a copy and pasted version of the txt file i used as input. It is saved in the Unicode format.
    &#30340;[de] <grammatical particle marking genitive as well as simple and composed adjectives>; &#25105;* w&#466;de my; &#39640;* g&#257;ode high, tall; &#26159;* sh�de that's it, that's right; &#26159;...* sh�...de one who...; &#20182;&#26159;&#35828;&#27721;&#35821;*. T&#257; sh� shu&#333; H�ny&#468;de. He is one who speaks Chinese. [d�] &#30446;* m�d� goal [d�] true, real; *&#30830; d�qu� certainly
    &#19968;(A&#22777;)     [y&#299;] one, a little; &#31532;* d�-y&#299; first, primary; &#30475;*&#30475; k�ny&#299;k�n have a (quick) look at [y�] (used before tone #4); *&#20010;&#20154; y� g� r�n one person; *&#23450; y�d�ng certain; *&#26679; y�y�ng same; *&#26376;y�yu� January [y�] (used before tones #2 and #3); *&#28857;&#20799; y�di&#462;nr a little; *&#20123; y�xi&#275; some {Compare with &#24186;(F&#20040;) y&#257;o, which also means "one"}
    &#26159;     [sh�] to be, *&#19981;*? sh�bush�? is (it) or is (it) not?; *&#21542; sh�f&#466;u whether or not, is (it) or is (it) not?

    Sorry, but i do not understand this post at all... Can anyone explain it to me? Is he saying my IDE is running on something other than Unicode?
    PS: I tried one of the Scanner constructors that takes a charset parameter. That fixed the odd output! However, every Chinese character has been replaced with a question mark. (It was a series of weird characters before i used the constructor with a charset parameter.)

  • How to parse data from a text file with no convenient delimiters?

    I need to read data from a text file.  This file contains one line of data with the repeating pattern "time 00 ADVar2: ___ Height: ____ time 01 ADVar2: ___ Height: ___ ..."  I need LabView to parse out the "time" and "height" values, build an array with the values, and graph the correlation on an X&Y plot.  Does Labview have an automated way to read to the input data file and parse out the correct values, even without convenient delimiters?  Thank you.

    You actually do have a convenient delimiter: "time". Thus, you can make an array using that as the delimiter. Only caveat is that the first array element will be empty. Then you can conveniently use the Scan From String function in a for-loop. Something like this:
    Message Edited by smercurio_fc on 11-21-2008 03:13 PM
    Attachments:
    Example_VI.png ‏9 KB

  • Globally Replacing a Noisy Media File with a Cleaned Up File in FCE

    I'm working on a project where I have found that one of my master clips has an audio issue. I've used subclips from this master clip in many places in my video. I'd like to know if thee is a way to process the audio of this master clip and have FCE pickup the cleaned up version of the media automatically for all the subclips used in my sequence. I've found a noise removal effect in a program called Audacity that works quite well to get rid of the noise in my master clip. I'm just not sure about the workflow to get the cleaned up file back into my FCE timeline. Audacity is supposed to work as an external editor in FCE, but haven't been able to get this to work correctly. Here's my proposal:
    1. Place my master clip on new sequence and export the audo tracks to an AIFF file.
    2. Process this file in Audacity using the Audacity Noise Removal effect and save to a .AIFF file.
    3. Import this clean .AIFF file back into FCE.
    4. Repace the audio on the timeline with the cleaned up audio file.
    5. Export this sequence to QTMovie.
    6. Exit FCE and using Finder, replce the original master clip media file in the Capture Scratch directory with the new file with the identical name as the original file
    7. Re launch FCE and hope the program picks up the new file like nothing had changed.
    Does anyone know if this can work as a way to do a global replace on a mdeia file tht needed cleaning up.
    Doug

    Should work as long as both files are the exact same length - the alternative is moving your original file to a new location then using the reconnect menu to navigate to the edited clip.

Maybe you are looking for

  • How to count the number of rows in a cube!!??

    Experts, I can somebody tell me how do I count the number of rows in my cube when i am using listcube???.. Thanks Ashwin

  • Is Maps App Working Again?

    Like others, I found the Maps application severely flawed once upgrading to ios 6.x. More than once I drove WAY out of my way on a wild goose chase due to inaccurate mapping. I finally threw in the towel and downloaded both GoogleMaps and MapQuest ap

  • Heart rate sensor

    hello There, i bought the  xperia Z1because off its ipx features and to use it as a heartrate monitor during sports. as I used to do with my samsung galaxy S2. however the bluetooth heartrate sensor doesn't function on the xperia Z1. does anyone know

  • System check on duplication of miro

    Hi expert I want to system to give a check when a enduser trying to do miro for which,  miro have been already posted. Regard Nabil

  • EREC- Candidate Registration Page

    Hi Experts, Is it possible to have different registration page for different region? my requirement is that for APAC i want the registration page to have fields like "date of birth" and "passport no." in the fields, whereas in US and Europe, i dont w