Search given string array and replace with another string array using Regex

Hi All,
I want to search the given string array and replace with another string array using regex in java
for example,
String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
String fromValue[] = {"you", "search", "for", "any"}
String toValue[] = {"me", "dont search", "never", "trip"}
so the string "you" needs to be converted to "me" i.e you --> me. Similarly
you --> me
search --> don't search
for --> never
any --> trip
I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
One Single regular expression which matches the pattern and solve the issue.
the output should be as:
If me wish to don't search never trip etc...,
Please help me to resolve this.
Thanks In Advance,
Kathir

As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
import java.util.regex.*;
public class Test
  static final List<String> oldWords =
      Arrays.asList("you", "search", "for", "any");
  static final List<String> newWords =
      Arrays.asList("me", "dont search", "never", "trip");
  public static void main(String[] args) throws Exception
    String str = "If you wish to search for any of these characters, "
        + "they must be preceded by the character to be interpreted";
    System.out.println(doReplace(str));
  public static String doReplace(String str)
    Pattern p = Pattern.compile("\\b\\w+\\b");
    Matcher m = p.matcher(str);
    StringBuffer sb = new StringBuffer();
    while (m.find())
      int pos = oldWords.indexOf(m.group());
      if (pos > -1)
        m.appendReplacement(sb, "");
        sb.append(newWords.get(pos));
    m.appendTail(sb);
    return sb.toString();
} This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

Similar Messages

  • How to find a word and replace with another

    hello,
    i just finished implementing a new website. I have about 20
    pages and lots of content. Last second, I am told that they need to
    change one word with another through out the website. Since there's
    so much text content, I was wondering if Dreamweaver has a feature
    like the Microsoft Word, in which I could type in that word and
    automatically replace it with another - through out the page.
    Thnx
    Ash

    Find and Replace....
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "asli" <[email protected]> wrote in message
    news:ekki09$5m2$[email protected]..
    > hello,
    >
    > i just finished implementing a new website. I have about
    20 pages and lots
    > of
    > content. Last second, I am told that they need to change
    one word with
    > another
    > through out the website. Since there's so much text
    content, I was
    > wondering if
    > Dreamweaver has a feature like the Microsoft Word, in
    which I could type
    > in
    > that word and automatically replace it with another -
    through out the
    > page.
    >
    > Thnx
    >
    > Ash
    >

  • IDVD looses original sound track and replaces with another sound track

    I have another issue. I have this one iMovie file that I downloaded from my MiniDV. I have added titles and transitions to it. When I click on the iDVD to go to the iDVD program and burn it, it takes the audio track of the last DVD I had burned and combines that audio track with the iMovie file I just brought over. I have wasted at least 4 DVDs but with no luck. Do you know what is causing it. I have tried to delete all the instance for that movie from the iDVD and restart but it still does the same thing. I also "play" it on iDVD before burning it and it has the correct audio but as soon as I burn it, it goes through 5 processes and burns it with my video and the audio is replaced with the audio from the last burn!!!
    Please help.
    Thanks. Anil Dalia, NJ

    Thank you for the kind words!
    Merry Christmas to you!
    Sue
    iMac PPC G5 20, iMac 17 Flat Panel G4   Mac OS X (10.3.9)   1 G RAM all around

  • Can i remove white sky and replace with another

    hi, im new to elements and photo editing, is there an easy to understand way of removing a whashed out white sky and replacing it with a blue/white cloud style of sky, i already have a donor sky.thanks for any advice given, ive got v7

    Make a selection of a segment of the donor sky with one of the selection tools
    Go Edit>copy
    Open the picture with the washed out sky
    Go to Edit>paste. This will put the donor selection on its own layer. Position it with the move tool over the old sky
    Set blend mode of this layer to darken
    Set foreground color chip (lower left) to white
    Drag foreground to transparent linear gradient from below up to top of tree line (if there are trees)
    With soft white brush, at reduced opacity, paint horizon on a new layer at top of stack. Horizon should be lighter than rest of sky..
    HTH

  • How to cut out part of an image and replace with another?

    ok, i'm a newbie to image editing, and i want to cut out a persons face in a picture and put in another face on the picture. i'm sure this is pretty simple, i just have no idea where to start. can someone point me in the right direction? thanks!

    Aperture is not a pixel editor, which is what you need. Photoshop is the app used for this, but it's cost is several times that of AP! As suggested in the second post, look into Photoshop Elements, a slimmed-down and much cheaper version of Photoshop. [I don't use Elements, so if someone knows that it can't do area copies from one pic to another, please join the conversation!]
    And get a good book on Photoshop or Elements, there's a huge learning curve involved. I'd suggest going to a book shop, pulling a few such books off the shelf and check their index for editing techniques. Sometimes you'll find one book that gives you the exact step-by-step instructions for doing what you want. Then there'll be others that don't get into the topic or do a poor job.

  • Delete a string part and replace by another one

    Hi,
    How can i delete a part of my string ?
    Thx

    REM ========== script T1.sql =============================================
    set verify off
    def A='0.000;0.000;1.000;'
    def B='0.000;'
    def C='2.000;'
    def occ=2
    select
           '&A'  OLD
          ,substr('&A' , 1, instr('&A','&B', 1, &occ) - 1)          X1
          ,substr('&A' , instr('&A','&B', 1, &occ),  length('&B') ) X2
          ,substr('&A' , instr('&A','&B', 1, &occ) + length('&B') ) X3
          ,   substr('&A' , 1, instr('&A','&B', 1, &occ) - 1)
           || '&C'
           || substr('&A' , instr('&A','&B', 1, &occ) + length('&B')) NEW
      from dual
    REM ======================================================================
    SQL> start T1
    OLD                X1     X2     X3     NEW
    0.000;0.000;1.000; 0.000; 0.000; 1.000; 0.000;2.000;1.000;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Replaces all occurnces of one String with another String in a given source

    Hi all I had found that there is a lot of interest int this topic. there is a little piece of code that I wrote for myself recently, so I fgigured that it might be helpful for some...
    This method will scan through a string "source", find all of the occurances of a String "before" and replace them with the "after".
    Enjoy :-)
    public static String replace(String source, String before, String after)
    StringBuffer sb = new StringBuffer(source);
    int startpos = source.indexOf(before);
    int endpos = startpos + before.length();
    int i = startpos;
    while( i > -1 )
         if( startpos > -1 && endpos <= source.length() )
         source = sb.replace(startpos, endpos, after).toString();
         int lastReplace = source.lastIndexOf(after) + after.length();
         if(lastReplace <= source.length())
              startpos = source.substring(lastReplace, source.length() ).indexOf(before);
                   endpos = startpos + before.length();
                   i = startpos;
         else
              i = source.length();
         else
              i = -1;
    return source;
    Oh yeah if you want, you can visit my site http://www.infobrokery.com it is where this code is used to replace the text URL with html.

    Since 1.4 the String class has a replaceAll method ...

  • How to replace a substring that starts with and end with another substring?

    Hi,
    I am trying to parse data from HTML tables. First I want to remove all useless tags like <font>. Now, how can I remove substrings like-
    *<font face="Verdana, Arial, Helvetica, sans-serif" size="1">My_Data_to_parse</font>*
    I was searching for any method which replaces a substring what starts with a substring (in this case "<font") and ends with another substring (in this case ">") . Is there any method like that? Or any better solution?
    Another situation like the following-
    *<td align="left" height="30" width="100%">*
    In this case I want to remove all the height, align , width etc and make it as simple as "<td>". How can I do that?
    Finally, all I am trying to do just to parse data from the tables in a html file. Is there any parser API or library to help me do that? Or to bring the data down to array from the tables based on table structure? Please suggest me.
    Thanks in advance.

    probably the best place to start is to search for the "<keyword" of all of the html keywords, then search for the location of the next ">" - this will indicate the end of the <keyword> opening tag.

  • Replacing a special character in a string with another string

    Hi
    I need to replace a special character in a string with another string.
    Say there is a string -  "abc's def's are alphabets"
    and i need to replace all the ' (apostrophe) with &apos& ..which should look like as below
    "abc&apos&s def&apos&s are alphabets" .
    Kindly let me know how this requirement can be met.
    Regards
    Sukumari

    REPLACE
    Syntax Forms
    Pattern-based replacement
    1. REPLACE [{FIRST OCCURRENCE}|{ALL OCCURRENCES} OF]
    pattern
              IN [section_of] dobj WITH new
              [IN {BYTE|CHARACTER} MODE]
              [{RESPECTING|IGNORING} CASE]
              [REPLACEMENT COUNT rcnt]
              { {[REPLACEMENT OFFSET roff]
                 [REPLACEMENT LENGTH rlen]}
              | [RESULTS result_tab|result_wa] }.
    Position-based replacement
    2. REPLACE SECTION [OFFSET off] [LENGTH len] OF dobj WITH new
                      [IN {BYTE|CHARACTER} MODE].
    Effect
    This statement replaces characters or bytes of the variable dobj by characters or bytes of the data object new. Here, position-based and pattern-based replacement are possible.
    When the replacement is executed, an interim result without a length limit is implicitly generated and the interim result is transferred to the data object dobj. If the length of the interim result is longer than the length of dobj, the data is cut off on the right in the case of data objects of fixed length. If the length of the interim result is shorter than the length of dobj, data objects of fixed length are filled to the right with blanks or hexadecimal zeroes. Data objects of variable length are adjusted. If data is cut off to the right when the interim result is assigned, sy-subrc is set to 2.
    In the case of character string processing, the closing spaces are taken into account for data objects dobj of fixed length; they are not taken into account in the case of new.
    System fields
    sy-subrc Meaning
    0 The specified section or subsequence was replaced by the content of new and the result is available in full in dobj.
    2 The specified section or subsequence was replaced in dobj by the contents of new and the result of the replacement was cut off to the right.
    4 The subsequence in sub_string was not found in dobj in the pattern-based search.
    8 The data objects sub_string and new contain double-byte characters that cannot be interpreted.
    Note
    These forms of the statement REPLACE replace the following obsolete form:
    REPLACE sub_string WITH
    Syntax
    REPLACE sub_string WITH new INTO dobj
            [IN {BYTE|CHARACTER} MODE]
            [LENGTH len].
    Extras:
    1. ... IN {BYTE|CHARACTER} MODE
    2. ... LENGTH len
    Effect
    This statement searches through a byte string or character string dobj for the subsequence specified in sub_string and replaces the first byte or character string in dobj that matches sub_string with the contents of the data object new.
    The memory areas of sub_string and new must not overlap, otherwise the result is undefined. If sub_string is an empty string, the point before the first character or byte of the search area is found and the content of new is inserted before the first character.
    During character string processing, the closing blank is considered for data objects dobj, sub_string and new of type c, d, n or t.
    System Fields
    sy-subrc Meaning
    0 The subsequence in sub_string was replaced in the target field dobj with the content of new.
    4 The subsequence in sub_string could not be replaced in the target field dobj with the contents of new.
    Note
    This variant of the statement REPLACE will be replaced, beginning with Release 6.10, with a new variant.
    Addition 1
    ... IN {BYTE|CHARACTER} MODE
    Effect
    The optional addition IN {BYTE|CHARACTER} MODE determines whether byte or character string processing will be executed. If the addition is not specified, character string processing is executed. Depending on the processing type, the data objects sub_string, new, and dobj must be byte or character type.
    Addition 2
    ... LENGTH len
    Effect
    If the addition LENGTH is not specified, all the data objects involved are evaluated in their entire length. If the addition LENGTH is specified, only the first len bytes or characters of sub_string are used for the search. For len, a data object of the type i is expected.
    If the length of the interim result is longer than the length of dobj, data objects of fixed length will be cut off to the right. If the length of the interim result is shorter than the length of dobj, data objects of fixed length are filled to the right with blanks or with hexadecimal 0. Data objects of variable length are adapted.
    Example
    After the replacements, text1 contains the complete content "I should know that you know", while text2 has the cut-off content "I should know that".
    DATA:   text1      TYPE string       VALUE 'I know you know',
            text2(18)  TYPE c LENGTH 18  VALUE 'I know you know',
            sub_string TYPE string       VALUE 'know',
            new        TYPE string       VALUE 'should know that'.
    REPLACE sub_string WITH new INTO text1.
    REPLACE sub_string WITH new INTO text2.

  • How to replace a particular striing with another string in jtextpane

    how to get replace a particular string with another string of a jtextpane without taking the text in a variable using getText() method .

    Thanks for your answer,
    "relevant object" means for you datasources, transfer rules and transformations ?
    With the grouping option "Save for system copy" I can't take easily all datasources, and others objects
    Will I have to pick all object one by one ?
    What would be the adjustement in table RSLOGSYSMAP ? For the moment it's empty.
    Regards
    Guillaume P.

  • Replace a string with another string in a file

    I have to replace a string with another string. Say for example in a html file it got a line like,
    <a href="##"></a>
    now i want to replace this ## with the full derived path like
    "c;\\sample folder\\sample subfolder\\samplefile.html"
    can someone help me to do this?
    pls tell me from the file opening till closing the file.

    I have to replace a string with another string. Say
    for example in a html file it got a line like,
    <a href="##"></a>
    now i want to replace this ## with the full derived
    path like
    "c;\\sample folder\\samplesubfolder\\samplefile.html"
    can someone help me to do this?
    pls tell me from the file opening till closing the
    file.
    public class Buckel {
      final static String CONST = "c:\\sample folder\\samplesubfolder\\samplefile.html";
      public Buckel() {
      public static void main ( String[] argv )  throws Exception {
        int    idx = 0;
        String in  = "<a href=\"##\"></a>",   // We'll imagine this just gets here somehow. If it's on the i/p file then take the '\' out B4 and aft the '##'.
               out = "";
        idx = in.indexOf( "##" );
        if ( idx > 0 ) {
          out = in.substring( 0, idx ) + CONST + in.substring( idx+=2, in.length() );
        System.out.println( out );
    }

  • My iphone is synced and backed up with another computer which is now broken... and i have synced it with a new one but when i want to do anything itunes says all data will be erased and replaced with the current itunes library?what do i do?

    my iphone is synced and backed up with another computer which is now broken...i have synced it with my new computer  but it hasnt transfered anything over to itunes and when i try to add anything to my iphone it says all data will be erased and replaced with the current itunes? i dont want to lose all my apps and music.... i dont know how to go around this problem? i want to back it all up and sync it properly to my new computer so that is now my main computer , so i can add ring tones and music etc with out it erasing everything ive got. any answers would be great and muchly appreciated. thanks, im not sure what operating system my iphone has either.....

    It has always been very basic to always maintain a backup copy of your computer for just such an occasion.
    Use your backup copy of your computer to put everything on the new one.
    It sounds like you have failed to do this, which is not good at all.
    You will have to transfer your itunes purchases from your iphone.  Authorize your computer for your itunes account 
    About iTunes Store authorization and deauthorization
    Open itunes, plug in iphone, do NOT sync, click File>Transfer Purchases
    When you do sync you will lose your pics ( photo library - synced from your old computer), your itunes content ( music, apps, videos,etc) , your contacts and your calendars.  So do NOT sync yet.  This is why a backup copy is so important.
    Enter one unique contact and calendar entry on your computer.
    When you first sync, you should get the option to merger the data.  Choose it.
    If you want your pics, then you will need to e-mail them to yourself before you sync.  They will not be of the original quality as they are reduced when synced to iphone.
    When all is as goos as it can be, then backup your computer, and always maintain the backup.

  • When I delete com.apple.audio.SystemSettings.plist my audio/sound problems are solved. However when the file is replaced with another file, the sound is crappy and the quality is reduced. Can you please help me?

    When I delete com.apple.audio.SystemSettings.plist my audio/sound problems are solved. However when the file is replaced with another file, the sound is crappy and the quality is reduced. Can anyone please help me?
    Sincerely,
    Eric

    Run this when you have the problem and post the results here.
    EtreCheck
    This will tell us what is loaded

  • I wrote an 2500 words assignment and saved in Microsoft word 97-2003 and by mistake replaced with another word file.How can i retain my original work?

    I wrote an 2500 words assignment and saved in Microsoft word 97-2003 and by mistake replaced with another word file.How can i retain my original work? 

    Hi,
    Does this happen to all 97-2003 Word files?
    Word 2013 now has lots of updates compared with earlier version of Word, lots of features have been updated. Use Word 2013 to open documents created in earlier versions of Word (Word 97-2003 format), you will probably encounter unexpected problems,
    expecially for those heavily formatted files.
    We would suggest you to convert your document to the Word 2013 file format, then you will be able to access the new and enhanced features in Word 2013.
    Regards,
    Ethan Hua
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • I'm trying to replace a missing font and apparently it's a graphic.  It's not letting me replace with another font and click change.  I can't export until it's fixed and I need to fix / bypass as soon as possible.

    I'm trying to replace a missing font and apparently it's a graphic.  It's not letting me replace with another font and click change.  I can't export until it's fixed and I need to fix / bypass as soon as possible.

    Go find the graphic in question, and open it in its native program. The problem will have to be fixed there.

Maybe you are looking for