Replace n:th string

Anyone have a nice suggestion for how to replace the n:th string in a string.
Example lets say we have text = "wooho wooho wooho".
And i want to call text.replace("wooho", "blaha", 2);
Which would replace the second occurence in the string so that it would return "wooho blaha wooho".
Any suggestions?

Fixed it! Wasn't so hard after all :P
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringReplacer {
     public static String replaceNth(String text, String regexp, String replace, int n){
          Pattern p = Pattern.compile(regexp);
          Matcher m = p.matcher(text);
          StringBuffer sb = new StringBuffer();
          int i=0;
          while (m.find()) {
               if (n == i){
                    m.appendReplacement(sb, replace);
                    break;
               i++;
          m.appendTail(sb);
          return sb.toString();
     public static void main(String[] args){
          String text = "aaaa woohoo fdsfd woohoo fdsfds woohoo fjdskf";
          String r = replaceNth(text, "woohoo", "blaha", 1);
          System.out.println(r);
}

Similar Messages

  • Two finger swipe replaces google search string

    MBP with Safari 6.0 experiencing this problem.  Another user was experiencing the issue here:
    http://www.ehmac.ca/mac-iphone-ipad-ipod-help-troubleshooting/99937-safari-two-f inger-swipe-bug-replaces-google-search-string-os-10-7-3-a.html
    I don't know where the bug reports are to follow up on it and I haven't seen any patches for it.  Any advice?  Specifically, I'd like to know how to file the bug (in case I find another) and to follow up on any existing issues.
    TIA,
    Scott

    Is there no place to track the status of the report or see any other outstanding issues so I don't bother filing duplicates?
    Never heard of such a function here. This method gets feedback to the people who count but it is completely behind the scenes. Part of Apple's "cards close to the chest" method of doing pretty much everything. You should have been looking at the "don't expect a response" screen after you hit the submit button on your bug report.
    If there is something that needs clarification, I suspect they will use e-mail to ask for it, but don't stay home waiting!
    Have you read Walter Isaacson's  biography of Steve Jobs? Things like this took on a new--if not satisfying--perspective for me after reading it. So far, it has persisted in their corporate culture in the after-Steve era..

  • How Can I replace newScale Text Strings with Custom Values?

    How Can I replace newScale Text Strings with Custom Values?
    How can I replace newScale text strings with custom values?
    All  newScale text is customizable. Follow the procedure below to change the  value of any text string that appears in RequestCenter online pages.
    Procedure
    1. Find out the String ID of the text string you would like to overwrite by turning on the String ID display:
    a) Navigate to the RequestCenter.ear/config directory.
    b) Open the newscale.properties file and add the following name-value pair at the end of the file:res.format=2
    c) Save the file.
    d) Repeat steps b and c for the RmiConfig.prop and RequestCenter.prop files.
    e) Stop and restart the RequestCenter service.
    f) Log  in to RequestCenter and browse to the page that has the text you want  to overwrite. In front of the text you will now see the String ID.
    g) Note down the String ID's you want to change.
    2. Navigate to the directory: /RequestCenter.ear/RequestCenter.war/WEB-INF/classes/com/newscale/bfw.
    3. Create the following sub-directory: res/resources
    4. Create the following empty text files in the directory you just created:
    RequestCenter_0.properties
    RequestCenter_1.properties
    RequestCenter_2.properties
    RequestCenter_3.properties
    RequestCenter_4.properties
    RequestCenter_5.properties
    RequestCenter_6.properties
    RequestCenter_7.properties
    5. Add the custom text strings to the appropriate  RequestCenter_<Number>.properties file in the following manner  (name-value pair) StringID=YourCustomTextString
    Example: The StringID for "Available Work" in ServiceManager is 699.
    If you wanted to change "Available Work" to "General Inbox", you  would add the following line to the RequestCenter_0.properties file
         699=General Inbox
    Strings are divided into the following files, based on their numeric ID:
    Strings are divided into the following files, based on their numeric ID:
    String ID  File Name
    0 to 999 -> RequestCenter_0.properties
    1000 to 1999 -> RequestCenter_1.properties
    2000 to 2999 -> RequestCenter_2.properties
    3000 to 3999 -> RequestCenter_3.properties
    4000 to 4999 -> RequestCenter_4.properties
    5000 to 5999 -> RequestCenter_5.properties
    6000 to 6999 -> RequestCenter_6.properties
    7000 to 7999 -> RequestCenter_7.properties
    6. Turn off the String ID display by removing (or commenting out) the line "res.format=2" from the newscale.properties, RequestCenter.prop and RmiConfig.prop files
    7. Restart RequestCenter.
    Your customized text should be displayed.

    I've recently come across this information and it was very helpful in changing some of the inline text.
    However, one place that seemed out of reach with this method was the three main buttons on an "Order" page.  Specifically the "Add & Review Order" button was confusing some of our users.
    Through the use of JavaScript we were able to modify the label of this button.  We placed JS in the footer.html file that changes the value of the butt

  • Replace the connection string in Excel MDS file

    I had MDS solution from one SQL Server 2012 to another - SQL Server 2014. I have configured Excel file with connection to MDS. How can I safely to replace the connection string in my Excel MDS file and the tables is not broken?
    from Moscow with money

    Hi,
    Excel is just used to manage data and create new entities and attributes. Why not first publish and close your excel before MDS upgraded to 2014? After the upgrade, reconnect new solution in your excel.
    thanks,
    Jerry

  • Replace " from the string

    Hi,  I am not able to remove " (double quotes) from a sting.
    I am using replace function in webi but getting error.
    example sting: Yellow stone"discovery"
    i have tried like this: =replace([varible];""";"")  but getting error. can anybody help me in removing the " from sting.
    Thanks.

    Description
    Replaces part of a string with another string
    Function Group
    Character
    Syntax
    string Replace(string input_string; string string_to_replace; string replace_with)
    EX:=Replace ([[variable]]; Char(34) ;"")
    Input
    input_string                     The input string 
    string_to_replace             The string within input_string to be replaced 
    replace_with                    The string to replace string_to_replace with. 
    Output
    The string with the part replaced
    Example
    Replace ("New YORK";"ORK";"ork") returns "New York"
    All the best,
    Praveen

  • Replace charcter from string in 46c

    Hi,
    If you could send me code for below scanerio that will be great.
    in 46c i have string '/ABCD/te_12' now i want to replace the '/' with '+'  and '_' with '|', can you tell me how to do this.
    thanks,
    john

    hi check the replace statement... hit F1 on replace and make ur code..
    Basic form
    REPLACE f WITH g INTO h.
    Addition
    ... LENGTH len (length specification for field f )
    Effect
    Replaces the first occurrence of the contents of field f in field h with the contents of field g . All fields are handled in their defined length; this means that closing blanks are not ignored.
    The return code value indicates whether the string f was found in h and replaced by g :
    SY-SUBRC = 0 String replaced.
    SY_SUBRC = 4 String not replaced.
    Example
        DATA FIELD(10).
        MOVE 'ABCB' TO FIELD.
        REPLACE 'B' WITH 'string' INTO FIELD.
    returns:
    FIELD = 'AstringCB', SY-SUBRC = 0
    Note
    The fields f and g in the REPLACE statement should not overlap. Otherwise, the result is undefined.
    Addition
    ... LENGTH len ... (length specification for field f )
    Effect
    Searches for the string f in the field h not in its (full) field length, but in the length len .
    Example
        DATA: PATTERN(5) VALUE 'ABC',
              LEN TYPE I,
              REPL_STRING(5) VALUE '12345',
              FIELD(12) VALUE 'abcdeABCDE'.
        REPLACE PATTERN WITH REPL_STRING
                        INTO FIELD.
    does not change FIELD , since 'ABC ' does not occur in abcdeABCDE ' .
        LEN = STRLEN( PATTERN ).
        REPLACE PATTERN LENGTH LEN
                        WITH REPL_STRING
                        INTO FIELD.

  • 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).

  • How to replace in a String

    I really want to know how to replace " in a String with replaceAll()
    I want to replace " with \"
    Unortunately I am not able to do it with :
    xml = xml.replaceAll("\"", "\\\"");Can u please suggest something
    thanks

    public class Test {
    public static void main(String[] args) {
       System.out.println("abc>def".replaceAll(">","\"+"));
    }Output:
    abc"+def

  • How to replace mixed chars string

    Hi All,
    I want to replace mixed chars string from each row and want to replace with new string.
    Ex : The existing string might be in different cases like "Abc string", "abc string", "aBC string". I want to search for all these string types and want to replace with new string "Abc string".
    Could anyone give suggestions on this.
    Thanks,
    Prakash

    [url http://download.oracle.com/docs/cd/E11882_01/server.112/e26088/functions149.htm#i1305521]REGEXP_REPLACE supports case insensitive replacing.
    REGEXP_REPLACE(source_string,'abc string','Abc string',1,0,'i')The *'i'* specifies case insensitive replacing, so it will find all of "Abc string", "abc string", "aBC string" :-)

  • How to used REGEXP_REPLACE  for replace part of string ?

    hi
    How can i replace part of string as following , i want to replace space in date by "-"
    SELECT
    REGEXP_REPLACE(upper('Daivd bought stuff by 2000 USD on 12 Sep 2012 from KL and left kl on 20 Sep 2012'),
    '[0-9]{1,2}[^0-9](JAN|FEB|MAR|APR|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[^0-9][0-9]{4}',
    ' ','-') "REGEXP_REPLACE"
    FROM DUAL;
    the output will be like this
    Daivd bought stuff by 2000 USD on 12-Sep-2012 from KL and left kl on 20-Sep-2012
    regards

    I thought the questions is answered.
    Your code will not work, because the alternate expression applies only to the four digit year and the month.
    If you want to recognize both date formats with one expressions, you have to group the complete expressions.
    The disadvantage of this would be, that the backreferences would not work in the same way because you would have more groups.
    I advice to use two separate regular expressions for this task.
    Take a look at the following example if you simply want to fill the gaps with -:
    with yourtable as
      select 'Daivd bought stuff by 2000 USD on 12 Sep 2012 from KL and left kl on 20 Sep 2012' text from dual union all
      select 'Daivd bought stuff by 2000 USD on Sep, 20 2012 from KL and left kl on Sep, 20 2012' text from dual 
    SELECT
    REGEXP_REPLACE(
    REGEXP_REPLACE(text,
    '([0-9]{1,2}) (JAN|FEB|MAR|APR|JUN|JUL|AUG|SEP|OCT|NOV|DEC) ([0-9]{4})','\1-\2-\3',1,0,'i'),
    '(JAN|FEB|MAR|APR|JUN|JUL|AUG|SEP|OCT|NOV|DEC), ([0-9]{1,2}) ([0-9]{4})','\1-\2-\3',1,0,'i') regexp_replace
    FROM yourtable;If you want same output-format for both date formats you could use this:
    with yourtable as
      select 'Daivd bought stuff by 2000 USD on 12 Sep 2012 from KL and left kl on 20 Sep 2012' text from dual union all
      select 'Daivd bought stuff by 2000 USD on Sep, 20 2012 from KL and left kl on Sep, 20 2012' text from dual 
    SELECT
    REGEXP_REPLACE(
    REGEXP_REPLACE(text,
    '([0-9]{1,2}) (JAN|FEB|MAR|APR|JUN|JUL|AUG|SEP|OCT|NOV|DEC) ([0-9]{4})','\1-\2-\3',1,0,'i'),
    '(JAN|FEB|MAR|APR|JUN|JUL|AUG|SEP|OCT|NOV|DEC), ([0-9]{1,2}) ([0-9]{4})','\2-\1-\3',1,0,'i') regexp_replace
    FROM yourtable;Edited by: hm on 25.09.2012 22:00

  • Replace char on String

    Hi All,
    String strValue = "ABC TPT 0694";
    My String is as shown above, I am looking for a way to replace char at byte 6 (position 6) with another Char in String.
    For example at location 6 it is "T" I want to replace it with char "O". can any one tell me how to do this

    String strValue = "ABC TPT 0694";
    char[] chars = strValue.toCharArray();
    chars[5] = 'O';
    strValue = String.valueOf(chars);

  • Replace a character/string

    hi all,
    i have string like c:\data\product, i wanted to get c:\\data\\product as output( "\" is replaced as "\\").how to do this.i tried replace string function but iam not the required output.
    thanks
    ravi

    You need to understand regex.
    http://www.regular-expressions.info/
    Even then, the way you need to escape the backslashes is not exactly intuitive:
    str = str.replaceAll("\\\\", "\\\\\\\\");\ is special to regex, so if you want a literal \ in your regex, you have to escape it with another \, but it's also special to the Java compiler. So to get a \ in the regex, you need to give it \\, but you also have to escape each of those for the compiler, so you get \\\\ to get a single literal \ in the regex.

  • Replace all ', , ' inside string

    i have long string and with pl/sql i want to replace all ', ,' with ', null,'.
    I can use replace function like:
    prepare_insert := replace(prepare_insert,', ,',', null,');
    but it will only replace first ', ,' not all. How can i replace all?

    5th database commandment:
    Thou shalt not create dynamic insert statements!
    I think using bind variables or the using clause in the execute immediate statement would solve the problem.
    But of cause you can do it also the hard (and slow) way.
    The problem is that your search string is not correct. It does include a leading "," and leaving ",". However if the leavaing "," is also the leading "," of the next replacement part then the function can't take this into account.
    Solution 1) Take care of this while building the string in the first place.
    While concating the pieces togeather use NVL(value,'null'). If you are sure that there s no value, then write NULL.
    Solution 2) Use a double replace
    with testdata as (select 'Test, , , , ''ABC''' txt from dual union all
                      select 'Test2, , , ''ABC''' txt from dual
    select txt
          ,replace(replace(txt,', ,',',null,'),', ,',',null,')
    from testdata;
    TXT               REPLACE
    Test, , , , 'ABC'     Test,null,null,null, 'ABC'
    Test2, , , 'ABC'     Test2,null,null, 'ABC'

  • Replacing a certaing string

    I need help with a program. Im talking about a Java application, not an internet based Java applet.
    Here are the steps:
    1)User inputs a string
    2)User inputs the word the user wants to change
    3)User inputs the word the user wants the word in #2 to be changed to.
    4)Find all occurences of the word and replace them with the word in #2.
    Can anyone help me with #4? If you can, could you also explain how it [the code you provide me] works? Thanks a lot

    Double posted and answered.
    http://forum.java.sun.com/thread.jspa?threadID=669028

  • Using Regular Expressions to replace Quotes in Strings

    I am writing a program that generates Java files and there are Strings that are used that contain Quotes. I want to use regular expressions to replace " with \" when it is written to the file. The code I was trying to use was:
    String temp = "\"Hello\" i am a \"variable\"";
    temp = temp.replaceAll("\"","\\\\\"");
    however, this does not work and when i print out the code to the file the resulting code appears as:
    String someVar = ""Hello" i am a "variable"";
    and not as:
    String someVar = "\"Hello\" i am a \"variable\"";
    I am assumming my regular expression is wrong. If it is, could someone explain to me how to fix it so that it will work?
    Thanks in advance.

    Thanks, appearently I'm just doing something weird that I just need to look at a little bit harder.

Maybe you are looking for

  • Can I have 2 different Apple ID's on one iTunes?

    I have my iPhone with my Apple ID on iTunes on my desktop Mac. My wife just got an iPhone that I would like to set up with her own Apple ID and iCloud account. Can I operate both phones on my one iTunes?

  • How to reduce image file size in spreadsheet

    I have created a spreadsheet that contains cells with small amounts of text, and images that I brought in from the Media Browser from iPhoto. This has caused the file size to become HUGE, on the order of 234 MB. Saving it as a pdf only reduces it to

  • CM Repository in a Share Folder

    Hi All,          Need your help in  a issue. I need to create a CM repository which should be available in the share folder so that all can see the reposiroty and the documents inside it. I have created the CM repository and also tried changing the R

  • Error with fusion middleware application

    I got this error when i try to access a jsff page in the application. I need your help. Thanks Error 500--Internal Server Error java.lang.ClassCastException: oracle.adf.controller.internal.binding.DCTaskFlowBindingDef cannot be cast to oracle.adf.con

  • I hear static, do you?  Could you check please?

    I have an 80 gig classic and have been wrestling with sound quality issues. I ripped some music using LAME at 320 kBit/s using EAC and it plays fine on my old Rio Carbon. But at precisely the same spot in the track every time, when a loud chorus star