Replace ever "anArray[1]" in a String...

Hello, I want to replace all "anArray[1]" without quotes in a String like "int x = anArray[1]; int y = anArray[2]; int z = anArray[1] + anArray[2];"
I tried this code:
String s = "int x = anArray[1]; int y = anArray[2]; int z = anArray[1] + anArray[2];";
s.replaceAll("anArray[1]", "1234");Though Java doesn't seem to replace anything...
Any hints?

The_Pointer wrote:
s.replaceAll("anArray[1]", "1234");Java doesn't seem to replace anything...
Any hints?[String.replaceAll()|http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29]
Replaces each substring of this string that matches the given [regular expression|http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum] with the given replacement.
In a regex "[" and "]" have special meaning - try "anArray\\[1\\]"(I know Encephalopathic already replied but the forum seems to mung double-backslash outside code blocks.)
Also, Strings are immuable, so it
Returns:
    The resulting String

Similar Messages

  • [JS - CS3]  Can't REPLACE A with B within a string? Help Please...

    Hello Experts,
    First off - I'm a newbee to all this JS and especially with CS3.
    I have a string: '
    b myDocumentName
    which can have it's value as: '
    b 00000en_ Generator WX/WY
    Problem is, backshlashes ( / )are a bad thing for me...
    b Question:
    How can I do a 'replace' operation to replace the '/' from the string with a '_'?
    I have at the moment:
    > var myDocSaveName = oneResult[3]+oneResult[4]+oneResult[5];
    > myDocSaveName.replace(what "/", with "");
    > myDoc.save ("C:/DATA/"+myDocSaveName, undefined, undefined, true)
    I get an error Nr. 25... Offending text:"/"
    What am I doing wrong?

    'what' and 'with' are the names of those arguments. They should not be included in the statement:
    myDocSaveName.replace("/", "");
    But that still won't work because replace doesn't operate on a string in situ, it returns the modified string. So:
    myDocSaveName = myDocSaveName.replace("/", "");
    This too has its limitations. It'll change only the first instance of "/", not all of them. To change all of them, you need to restate the 'what' as a RegExp:
    myDocSaveName = myDocSaveName.replace(/\//g, "_");
    A RegExp literal is delimited by the "/" character, so to have it, alone, as the character to be sought you must use the backslash to escape the character. Then, to indicate you want the replace to happen globally within the string, you add the 'g' after the RegExp.
    Dave

  • 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 can i replace backslashes with fowardslashes in a String

    Hi all,
    I hope someone can help me with this stupid problem iv been having, i need to replace all the backslashes in a String with forwardslashes.
    The method replace() doesnt work because it uses Chars, also i cant use replaceAll() because im restricted to using jdk1.3.
    I would really appreciate some help here,
    Thanks

    Or in other words, I have no idea what you're talking about:
    public class Foo {
         public static void main(String[] args) {
              String s = "string with \\ back \\ slashes \\ in \\ it !";
              System.out.println(s.replace('\\','/'));
    }

  • Replace all special characters in a String with underscore

    I have a String which contains some special characters even(!,$,@,*....).
    I need to replace all the special characters with _ in my String. I do have an idea of using String.replace() and analogous forms, but I would be thankful if anyone can suggest me of a better and an efficient way.
    regards,
    fun_one

    Kaj,
    Thx for your earnest reply. I did have a peep into the API on this method. But the regular expression that I need to use here was beyond my understanding. It did specify some regex that I put to use (something like myString("\D","_"), assuming that I need to replace all non-digit characters ), but it really did not help me getting the result.
    Would you spare some code for me reg. the usage of regular expressions in such a scenario?
    cheers,
    fun_one

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

  • How do I replace a single instance of a string?

    I'm trying to replace a certain string in a text file. The problem is, there is other data in the text file that is being affected by the replace() function, since replace() replaces each substring that fits the pattern it's looking for. I want my replacement function to target one single instance of something, at one specific instance, and to leave the rest of my text alone.
    Any thoughts on how I'd do that?

    I don't see how to do it with a String direclty without making silly copies.
    But it seems you could use a StringBuilder and its method replace(int start, int end, String str).
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html#replace(int,%20int,%20java.lang.String)

  • Replacing the same value in a string with varying values

    If I have a string:
    "%s is the %s I am referring to"
    and - I want to replace the %s occurrences with DIFFERENT values... what's the best way to do this.
    I was thinking parsing it into seperate strings using substr and instr but, I'm not sure if that's overkill or not.
    Replace is ideal but - it replaces every occurrence so - you can state just replace the first occurrence with one value and the second with another (i.e. if the desired result after replacing the above string was supposed to be "This is the string I am referring to"
    Any help is appreciated.
    Thanks

    Hi,
    wtlshiers wrote:
    If I have a string:
    "%s is the %s I am referring to"
    and - I want to replace the %s occurrences with DIFFERENT values... what's the best way to do this.Whenever you have a question, please post CREATE TABLE and INSERT statements for a little sample data, and the results you want from that data.
    Explain how you get those results from that data.
    Always say which version of Oracle you're using (e.g. 11.2.0.3.0).
    See the forum FAQ {message:id=9360002}
    I was thinking parsing it into seperate strings using substr and instr but, I'm not sure if that's overkill or not.Depending on your requirements, you might need to do that.
    Replace is ideal but - it replaces every occurrence so - you can state just replace the first occurrence with one value and the second with another (i.e. if the desired result after replacing the above string was supposed to be "This is the string I am referring to"As you said, REPLACE changes all occurrences. There's no way to tell it (for example) to change only the first one.
    REGEXP_REPLACE, is a lot more flexible. It does have an option for giving a specific occurrence, but you may not even need that feature. You might just want something like
    REGEXP_REPLACE ( '%s is the %s I am referring to'
                , '(.*)%s(.*)%s(.*)'
                , '\1This\2string\3'
                )It all depends on your data and your requirements.
    Are the new values (such as 'This' and 'string') fixed, or can they change from row to row?
    Will you always have 2 (or some known number) of '%s's in the original string?
    Does '%' always signal something that is to be replaced? If not, how can you tell when it does and when it doesn't?
    Does 's' always come right after '%'? If not, what are the possibilites, and what do the different characters signify?

  • Replacing words in an array of strings

    hi
    im trying to create a method that takes three arrays of strings as parameters and replaces some words in one of them
    heres my code
    class A0
    public static void main (String[] args)
    int index;
    String[] in = {"life","is","a","bowl","of","pits"};
    String[] what={"pits", "bowl"};
    String[] with={"chocolates", "box"};
    String[] result=new String [in.length];
    result=findAndReplace(in, what, with);
    for (index=0;index<in.length;index++)
    System.out.print(result[index]+" ");
    static String[] findAndReplace (String[] in, String[] what, String[] with)
    int index1;
    int index2;
    String[] newString= new String [in.length];
    for (index1=0;index1<in.length;index1++)
    for (index2=0;index2<what.length;index2++)
    if (in[index1]==what[index2])
    newString[index1]=with[index2];
    else
    newString[index1]=in[index1];
    return newString;
    ok so it's supposed to print life is a box of chocolates, only it prints life is a box of pits???pls help

    i figured it out

  • How to replace a regular exepresion in a string in power shell

    Hi,
    Not able to replace "\X25" with "%" in powershell script.
    $new = $inst1
    $word = '\X25'
    also tried
    $word = "\X25"
    $replacement = "%"
    $newText = $new -replace $word,$replacement
    following error has been occurred:
    The regular expression pattern \X25 is not valid.
    At C:\TWClient-Build\rgx.ps1:15 char:1
    + $newText = $new -replace $word,$replacement
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (\X25:String) [], RuntimeException
        + FullyQualifiedErrorId : InvalidRegularExpression
    Thank You

    As noted in other posts, it's failing because the '\' is a reserved character and needs to be escaped.  There are other reserved characters that will also need to be escaped if you need to match them in your regular expression.
    The [regex] class offers an static Escape() method that you can use to help you escape the reserved characters when doing a literal match:
    $find = '\X25'
    $Regex = [regex]::Escape($find)
    $Regex
    \\X25
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Replacing a single occurance in a string

    if i do string.replaceAll(old,new) then it replaces every occurance in the string
    how can i only replace the first found occurance in the string or even better specify where in the string i want to start looking
    so if i have
    hello hello hello hello
    i can say
    string.replace(5,"hello", "yellow")
    and it will give me
    hello yellow hello hello

    ive come up with this
    SNIP
    it seems to be doing the trick (so far)Good one! I guess the same is actually done with StringBuffer.replace()
    jTPdisplay.setText(new StringBuffer(f).replace(pos, pos+f.length(), r).toString());It should be something like this. :)

  • REGEXP_REPLACE - replace '\n''s inside a xml string

    I have this xml string and i need to replace the '\n' for one # but only the \n's inside the tag's not the first \n how do that with REGEXP_REPLACE?
    <?xml version="1.0" encoding="UTF-8"?>\n
    <ipb>
    <address>Rua são Joao\n
    Bragança
    </address>
    <calendar>
    1º Semestre:\n
    Início: 21/09/2009\n
    Fim: 19/02/2010\n
    Pausa Natal: de 21/12/2009 a 03/01/2010\n
    \n
    2º Semestre:\n
    Início: 22/02/2010\n
    Fim: 16/07/2010\n
    </calendar>

    Well, i'm no regular expression master, but no one's responded so i'll venture an answer (not using regular expression though).
    ME_XE?with data as
    select
    '<?xml version="1.0" encoding="UTF-8"?>\n
    <ipb>
    <address>Rua são Joao\n
    Bragança
    </address>
    <calendar>
    1º Semestre:\n
    Início: 21/09/2009\n
    Fim: 19/02/2010\n
    Pausa Natal: de 21/12/2009 a 03/01/2010\n
    \n
    2º Semestre:\n
    Início: 22/02/2010\n
    Fim: 16/07/2010\n
    </calendar>' as col1 from dual
    select
      replace(replace(replace(col1, '>\n', '~*~'), '\n', NULL), '~*~', '>\n') as new_col1
    from data;
    NEW_COL1
    <?xml version="1.0" encoding="UTF-8"?>\n
    <ipb>
    <address>Rua s??o Joao
    Bragan??a
    </address>
    <calendar>
    1?? Semestre:
    In??cio: 21/09/2009
    Fim: 19/02/2010
    Pausa Natal: de 21/12/2009 a 03/01/2010
    2?? Semestre:
    In??cio: 22/02/2010
    Fim: 16/07/2010
    </calendar>
    1 row selected.
    Elapsed: 00:00:00.17
    ME_XE?Just used the regular replace to decode the instances of \n you want to keep (using a string you're not likely to find in your source data) and then replaced all the \n's with null, then put back the /n replacing the string we subbed in before.
    If Michaels is around, maybe you'll get a flashy XML answer to your question ... sorry, but i'm not that much flash :)

  • Replace the first character in a String with blank

    String a = dgramRsp.getAddress().toString();
    a = a.replace('/','');The problem with the first statement is that it returns an ip address with a '/' in front of it. Like so.../192.168.0.190
    I need to get rid of the '/'. The replace won't work because it wants a character between the ' '. Thanks for your time.

    I had to think about it for a sec but yes you're
    right.
    InetAddress a = dgramRsp.getAddress();
    String b = a.getHostAddress();
    substring(1) would have worked, too, but it would have been redundant (removing a previously added slash).

  • How can I replace a certain position of a String?

    How can I do this?
    I have this string: "Hello World"
    Now I want it to have: "Hello Warld"
    I already know the position of the char to be replaced.

    Try StringBuilder/StringBuffer. You can set a character at a certain location.

  • Apostrophes are replaced by question marks in output string?

    Hi Guys
    I think this is an encoding problem but I cannot find it in the forum archives. My apostrophes are being replaced by question marks on my jsp output?
    Any idea why and how to get them back to apostrophes
    Cheers, ADC

    Guys, the 3rd party product has no trouble at all
    showing the apostrophes from the self-same database
    that I get question marks from.
    This MUST be an encoding issue, so anyone that knows
    about encoding and changing it please could you
    suggest something. You can take for granted that one
    way or another the character in the database IS an
    apostrophe as verified by viewing it via the 3rd party
    product we have.You said...
    In the SQL database view they come out as squares
    Were you referring to the normal applications that are available for viewing data for the database (like SQL*Plus or Enterprise Manager?)
    If yes, then if it was me then I would presume it was not an apostrophe and that the third party tool was mapping the real character to an apostrophe. A 'square' indicates an unusual character in viewers.
    Are you using EBCDIC? Unless EBCDIC is involved apostrophe has the same value in most if not all character sets because ANSI forms the lower range for most character sets. I know for example that Korean, Japanese and Chinese character sets use ANSI, as does unicode (with padded zeros for the wider ranges.)

Maybe you are looking for