How to use String.replaceAll(String regex, String replacement)?

hi,
I'd like to use the String.replaceAll call to replace all occurrences of a pattern in a string with a string inputted from the user.
The problem is that replaceAll seems process the replacement string first. For example, the code below won't work
public class StringTest {
     public static void main(String [] arg) throws Exception {
          String input = "oooIoooIooo";
          input=input.replaceAll("I","\\");
          System.out.println(input);
}So the only option seems to be to manually process the user input string into a form that can be accepted by String.replaceAll?
The only thing I can find from looking through the API is that you'd need to convert each backslash to a double-backslash?
is this the right thing to be doing?
thanks,
asjf

just to clarify, at the moment I think the solution is to do this
public class StringTest {
     public static void main(String [] arg) throws Exception {
          String input = "oooIoooIooo";
          String raw = "\\";
          input=input.replaceAll("I",raw.replaceAll("\\\\","\\\\\\\\"));
          System.out.println(input);
}

Similar Messages

  • How to use String.replace()?

    I have a string such as "ab:bc cd", i wanna get ride of the ':'and ' ', but how can i describe a null char in the replace(), thanks in advance.

    public class CharacterReplace
       public static void main (String args[])
          String temp = "ab:bc cd";          
          char newChar[] = new char[temp.length()];
          for(int i=0; i<temp.length(); i++)
          char ch  = temp.charAt(i);
          if((ch != ':') && (ch != ' '))newChar[i] = ch;
          String newString = new String(newChar);
          System.out.println("String after changing ->  " + newString);
    }Copy and paste the code and try it. It works.
    Vijay :-)

  • How to use string variable onside quotes

    Hi,
    i would like to know how to use string variable onside quotes. what i mean is if i have a LOV variable P_STATUS as character string.
    and in my PL/SQL function i give a query as
    Q AS VARCHAR2(1000) := 'SELECT * FROM EMP
    WHERE STATUS = :P_STATUS';
    Is this correct. I Know that the above statement works when the LOV is an integer, but when i use a character LOV return value the above statement does not work. how can i get in the character LOV value.
    Can someone help me please.
    Thanks,
    Philip.

    916753 wrote:
    Yes I tried binding all the values separately. It is working, but, I am trying to pass all values by variableBut you can't. The variable is holding a single string value.... that is just 1 value. Your binding are expecting multiple values. You can't bind 1 string value and expect Oracle to magically know how to break your string up into seperate values for the bind variables. What if one of your bind variables actually needed e.g. a comma seperated string as it's value? How would Oracle know that?
    You must bind each thing seperately. That's the way cursors work.
    , because i have more than 150 tables in which data will be load. that's why i m trying to create a unique procedure to load data one by one table. Otherwise I have to write individual procedures for per procedures.It's a hard life being a software programmer, but somebody's got to do it. Unfortunately there are too many people who try and write "generic" procedures and expect them to just work. I mean why don't Oracle just implement some SQL command so you can do...
    execute immediate 'load all my tables';save us all the hassle eh!? ;)
    when i write all the columns like
    execute immediate (insert_string) using rc1.TOLL_ID, rc1.LANE_ID, rc1.RECEIVED_DATETIME, rc1.LANE_QUERY, c1.EXECUTED_DATETIME
    but it is not possible to generate runtime variable thats why I m trying to assign all values to a single variable and use it like
    execute immediate (insert_string) using (v_string)
    how can I separate the values and ho to use it .Don't use execute immediate. Use the DBMS_SQL package instead and bind your values dynamically with loops to cover all the columns you need etc.

  • How to use string format in TextInput?

    How to use string format in TextInput?
    Ex.
    HH:MM:SS when typing message appear in 12:34:56 form.
    N,NNN when typing message appear in 1,234,567 form.

    look up for "Using formatters" in the FB help.
    Essentially you'll instantiate a format, NumberFormatter for
    numbers for example, and set it's properties like e.g. showing a
    thousand separator and then one some event of the TextInput --
    valueCommit for example -- you'll do something like:
    ti.text = nf.format(ti.text)
    this is would also give you opportunity to validate user
    input using the same formatter and valid event.
    ATTA

  • How to use string to substitude into a parameter ,look @ msg 4 more detail

    How to use a screenname from an array of strings of screennames to set it to current screen
    Example:
    //screens
    Form logo;
    List cat,sub;
    int back;//previous screen index
    public String SCREEN[]={"logo","cat","sub"};
    if (command=cmdBack) display.setCurrent(SCREEN[back]);
    how???,i don't want to type in the screen name as i want it to be able to keep track of the screen displayed.
    Please Help
    thanks

    hi...just one suggeation...u may like it ...
    u can use a stack , as and when u view a screen push it onto the stack and with each press of "back" button u pop out . this way the back button functionality works perfectly no matter how u navigate between screens .
    sanjib

  • How to use String toString?

    hey guys,
    I've 2-D array and i would like to printout using String toString method. I'v used that method to printout non-array values but I really don't know how to display 2-D array using the String toString method. Can someone please help me? thanks in advance!

    I do not understand your question. Please post
    whatever code you have and indicate where you are
    stuck.I'm sure you're aware of the String toString method which is often used to display the output in different classes without the main method.
    I've following code:
    public static int bingoCard [][] = new int[SIZE][SIZE]; 
    public BingoCard()   {
            Integer ran = 0;
            for (i = 0; i < SIZE; i ++) {
                 if (i == 0) {
                    min = 1;
                    max = 15;
                } else {
                    min = max + 1;
                    max += 15;
    //             System.out.println("Min: " + min + " " + "Max: " + max);
                // generate all 15 balls in this range
                for (j = min; j <= max; j++) {
                    bC.add(new Integer(j));               
    //             // randomize the 15 balls           
                for (j = 0; j < SIZE; j++) {
                    while (bingoCard[i][j] == 0) {
                        ran = (Integer)bC.removeRandom(); // get Integer object back
                        if (max <= 15 && (ran.intValue() >= 1 && ran.intValue() <= 15))
                            bingoCard[i][j] = ran.intValue();              
                        else if(max <= 30 && (ran.intValue() >= 16 && ran.intValue() <= 30))
                            bingoCard[i][j] = ran.intValue();           
                        else if(max <= 45 && (ran.intValue() >= 31 && ran.intValue() <= 45))
                            bingoCard[i][j] = ran.intValue();              
                        else if(max <= 60 && (ran.intValue() >= 46 && ran.intValue() <= 60))
                            bingoCard[i][j] = ran.intValue();             
                        else if(max <= 75 && (ran.intValue() >= 61 && ran.intValue() <= 75))
                            bingoCard[i][j] = ran.intValue();
    //                 System.out.println("Numbers in the card: " +  bingoCard[i][j]);
            bingoCard[2][2] = 0;       
    Now, i want to dipslay the bingoCard[][] using following method
    public String toString () { // return that array } instead of using following method which displays it for now
    public static void display () {
            for ( i = 0; i < SIZE; i++) {
                 System.out.print(" "+ columnTitles[i] +"   ");
            System.out.println(); 
            for (i = 0; i < SIZE; i++) {  
                for (j = 0; j < SIZE; j++) {               
                    System.out.print(" "+bingoCard[j] +" ");
    if (bingoCard[j][i] < 10)
    System.out.print(" ");
    System.out.println();
    Any help would be really apperciated. =]

  • How to use string functions (substr or ltrim or replace)  in OLAP universe.

    cost element (0COSTELMNT) - 10 CHAR
    Controlling area (0CO_AREA) - 4 CHAR
    [0COSTELMNT].[LEVEL01].[[20COSTELMNT]].[Value]
    cOST ELEMENT is compounded/prefixed with Controlling Area. I just want to see cost element without conrolling area in the BO report.
    Currenlty BO unierse is build based on bex query. I am able to suppress the compounding object in bex query by chaning controlling area to 'No display'. But still BO Webi report displaying compounded values in the report. (Bex report works as expected)
    eg: Current display in reort.
    controlling area/cost element.
    AB00/2222
    AB00/2223
    AB00/2224
    Wanted like  below:
    2222
    2223
    2224
    I think by using string fucntions (substring, ltrim or  replace etc.), I can get the required result. But I am having issues with syntax. I have used like below.
    substr(0COSTELMNT ; 5 ; 10)
    substr(0COSTELMNT; 5 ; Length(0COSTELMNT)-5)
    substr(0COSTELMNT; Pos(0COSTELMNT;"/")+1;10)
    ltrim(0COSTELMNT,'AB00/')
    What is the syntax for substring/replace functions in OLAP universe. Technical name of cost element in OLAP  universe is [0COSTELMNT].[LEVEL01].[[20COSTELMNT]].[Value].
    I want to fix this at universe level not at report level as  i am using cost element in filter/variable section of the report. Please provide me syntax for above example.

    Hi,
    In fact SAP BW MDX supports limited string manipulation and only with NAME and UNIQUENAME attributes.
    Here are some samples that you can use in universes:
    MID([0COSTELMNT].currentmember.NAME,1,4)
    LEFT([0COSTELMNT].currentmember.NAME,2)
    RIGHT([0COSTELMNT].currentmember.NAME,3)
    MID([0COSTELMNT].currentmember.UNIQUENAME ,1,4)
    LEFT([0COSTELMNT].currentmember.UNIQUENAME ,2)
    RIGHT([0COSTELMNT].currentmember.UNIQUENAME ,3)
    Didier

  • How to Use String Patterns?

    Hai all,
    I need help, In my project i am using String patterns.
    i need to search a string which contains special characters.
    Ex:
    1.Abstract{meaning}
    I have to search Abstract in this case.
    Another case is:
    2.Moon
    in this i Have to search Moon and
    so on.
    For this Source Code I had written is:
    string input = args[0];
    String pattern = "[0-9].*+\\{*\\}";
    String pattern1 = "[0-9].*";
    string line = "1.Abstract{meaning}";
    string line1 = "1.Moon";
    if( (Pattern.matches(pattern, line))||(Pattern.matches(pattern1, line1)) )
    Pattern p = pattern.compile("\\.");
    Pattern p1 = pattern.compile("\\{");
    String[] tokens = p.split();
    String[] tokens1 = p1.split();
    for(int i = 0; i < tokens.length ; i++)
    for(int j = 0; j < tokens1.length ; j++)
    if((tokens.equals(input))||(tokens[j].equals(input)))
    System.out.println(tokens[i]);
    System.out.println(tokens[j]);
    in this code it matching the 2nd case. it is not matchinf the 1st case.
    please help me.
    Thanks

    look up for "Using formatters" in the FB help.
    Essentially you'll instantiate a format, NumberFormatter for
    numbers for example, and set it's properties like e.g. showing a
    thousand separator and then one some event of the TextInput --
    valueCommit for example -- you'll do something like:
    ti.text = nf.format(ti.text)
    this is would also give you opportunity to validate user
    input using the same formatter and valid event.
    ATTA

  • How to use Microsoft Word's Find and Replace with HTML tags?

    Hello to all!
    I'm trying to figure out how to use the find and replace function in Word to replace html tags. I'd like to be able to change something like this:
    <span class="B01-K-ITAL">random text</span>
    To something like this:
    <em>random text</em>
    I want to replace the open and close tags without changing or interfering with the text between the tags. I'm pretty sure I should use wildcards, but I can't figure out how to use them properly.
    Anyone able to lend a hand?

    Here is my latest regular expression with Perl.   I think it matches the spirit of the request in the original post.
    Note, this isn't as easy as you think.  You need to code up the complete set of html rules in you implementation. You need to allow for a certain amount of mal-formed html.
    perl -0660pe 's^<[sS][pP][aA][nN]\s+class="B01-K-ITAL"\s*>(.*?)</[sS][pP][aA][nN]>^<em>$1</em>^gs' i.html >|o.html
    input text
     <html> <head>...</head> <body>I'd like to be able to change something like this: <span class="B01-K-ITAL">#1 one line</span> I want to replace the open and close tags without changing or interfering with the text between the tags. I'm pretty sure I should use wildcards, but I can't figure out how to use them properly. <p>note, this isn't as easy as you think.  You need to code up the complete set of html rules in you implementation. You need to allow for a certain amount of mal-formed html.</p> <span class="B01-K-ITAL">#2 don't be greedy</span> <span class="B01-K-ITAL">$3 multiline text</span> <span class="B01-K-ITAL">#4 multiline tag. I believe html allow a carriage return in white space of tags</span> <span class="B01-K-ITAL">#5 split after the class tag. optional white space</span> <sPan class="B01-K-ITAL">#6 mixed case tag</Span> <p>no text #7</p><span class="B01-K-ITAL"></span> <!-- Apparently, this is valid     http://www.positioniseverything.net/articles/cc-plus.html --> <!--[if IE]> <div id="IEroot"> <![endif]--> <p id="IE">This browser is IE.</p> <p id="notIE">This browser is not IE.</p><!--[if IE]> </div> <![endif]--></body> </html>
    output text
     <html> <head>...</head> <body>I'd like to be able to change something like this: <em>#1 one line</em> I want to replace the open and close tags without changing or interfering with the text between the tags. I'm pretty sure I should use wildcards, but I can't figure out how to use them properly. <p>note, this isn't as easy as you think.  You need to code up the complete set of html rules in you implementation. You need to allow for a certain amount of mal-formed html.</p> <em>#2 don't be greedy</em> <em>$3 multiline text</em> <em>#4 multiline tag. I believe html allow a carriage return in white space of tags</em> <em>#5 split after the class tag. optional white space</em> <em>#6 mixed case tag</em> <p>no text #7</p><em></em> <!-- Apparently, this is valid     http://www.positioniseverything.net/articles/cc-plus.html --> <!--[if IE]> <div id="IEroot"> <![endif]--> <p id="IE">This browser is IE.</p> <p id="notIE">This browser is not IE.</p><!--[if IE]> </div> <![endif]--></body> </html>

  • How to use string as a column name

    Hello,
    I have a fn getField() that returns a column delimited string - amt1,amt2 . I want to use this string as the column name in a second query on table MASTER_AMT and get the values for amt1 and amt2...so when i try....
    select getField( 'NPC_NOYTG' ) FROM MASTER_AMT
    WHERE ACTI_CODE = 'NPOR';
    the o/p i get is...
    GETFIELD('NPC_NOYTG')
    AMT1,AMT2,AMT3
    instead of...
    AMT1 AMT2
    500 0
    that i require.
    Any ideas on how to convert the string returned to a column name?
    Thanks very much
    rgds

    Try this ....
    In SQL*PLUS
    SQL> var ref_c refcursor
    --- Then type the follwing at SQL prompt
    declare
    cursor cur is
    select column_name
    from user_tab_columns a,
         (select upper(getField( 'NPC_NOYTG')) fld FROM MASTER_AMT
         WHERE ACTI_CODE = 'NPOR') col_lst
    WHERE
    instr(chr(44) || col_lst.fld || chr(44),chr(44) || a.COLUMN_NAME || chr(44) ) > 0
    AND table_name = 'MASTER_AMT';
    v_str varchar2(1000):= ' ';
    begin
    for c in cur loop
    v_str := v_str || c.column_name || ',' ;
    end loop;
    v_str := substr(v_str,1,len(v_str)-1);
    open :ref_c for
    'select ' || v_str || ' from master_amt';
    end;      
    --- after executing the above block, type the following at SQL prompt
    SQL > print ref_c
    Please let me know if this works for you. This should for any number of columns returned by the function.
    Shakti
    (http://www.impact-sol.com)
    (Developers of Guggi Oracle)

  • How to use string control as terminal window

    Hello All
    I am trying to create a terminal window in my VI and to do this i have a string control and a string indicator.
    I want the user to be able to write a command in the terminal and when hitting enter the control should update, but not before! I would
    like the user to be able to enter multiple commands without having to re-click the control with the mouse, so it has to stay in the
    control window. 
    The output from this string control is input to a invoke node to an external motor controller, which replies with a string input to the string indicator.
    Tried to do some event case, but not quite sure how I am going to detect only the enter command.
    Any ideas how to preceed?
    Thanks
    Regards
    Tommy
    Solved!
    Go to Solution.

    Yeah, in your event structure, look for an event of your string control called "key down"...on the left, there are several parameters coming up (char, vkey etc.) where you can use for example the char to look for char=13 (return).
    look here: http://zone.ni.com/reference/en-XX/help/371361B-01/lvprop/control_key_down/
    good luck
    christian 
    THINK G!! ;-)
    Using LabView 2010 and 2011 on Mac and Win
    Programming in Microsoft Visual C++ (Win), XCode (Mac)

  • How to use String to name objects

    Hello,
    I have an array of 100 Strings and I want to create 100 objects of a Class with same names as the ones in the Strings, is there any way to do it?
    I have searched the forum and I think it can be done with a Map Class, but I wonder if there is a more convenient way.
    Thanks,
    Kostas

    Any way other than actually putting them into the map? What did you have in mind? Some kind of zen map, perhaps? :-)
    This is exactly the sort of thing a map is for - mapping instances of one class to instances of another; in this case mapping strings to Resources. So this is almost certainly the best data structure.
    How you obtain the names and the Resources is another matter. Taking them in as separate arrays (which might have different lengths) may not be the best solution. A better solution might be to make the Resources able to identify themselves so you could add them to the Map and ask them for their names to use as the keys.
    Also, I notice that you're creating an array of these resources, but the array will be initialised with 100 (actually, 101 - 0..100) null pointers. This is probably not what you want. And even correctly initialising the array with Resources constructed through the default constructor might not be what you want. You could, maybe, wrap your map with another class which queries the map and lazily creates Resources for you if they don't already exist.

  • How to use string class?

    Hi, experts:
    Have you run HelloStrings sample in "Thinking in C++" book? The source code is following. But when I compile, it throws error:"string in not defined". How to write correct makefile? Thanks! /Denise
    //: C02:HelloStrings.cpp
    // The basics of the Standard C++ string class
    #include <string>
    #include <iostream>
    using namespace std;
    int main() {
    string s1, s2; // Empty strings
    string s3 = "Hello, World."; // Initialized
    string s4("I am"); // Also initialized
    s2 = "Today"; // Assigning to a string
    s1 = s3 + " " + s4; // Combining strings
    s1 += " 8 "; // Appending to a string
    cout << s1 + s2 + "!" << endl;
    } ///:~

    The most likely cause is that the "using namespace std;" line is missing from the file you are compiling, or commented out.
    Using C++ 5.6 and the exact file I listed earlier, I get this result:
    % CC -V hello.cc
    CC: Sun C++ 5.6 2004/06/02
    /set/mercury/dist/fcs.2/sparc-S2/opt/SUNWspro/prod/bin/c++filt: Sun C++ 5.6 2004/06/02
    ccfe: Sun C++ 5.6 2004/06/02
    ld: Software Generation Utilities - Solaris Link Editors: 5.9-1.377
    Copy/paste the hello.cc file I listed above and try compiling it.
    If you still get errors, your compiler was not installed correctly, or the installation has become corrupted.
    If you want to poke around a bit more before re-installing, try this:
    CC -H -c HelloStrings.cc |& grep string
    The -H option lists all the header files that were read. You should see this, assuming your compiler is installed in /opt:
    /opt/SUNWspro/prod/include/CC/Cstd/./string <------- string header
         /opt/SUNWspro/prod/include/CC/std/string.h
              /usr/include/string.h
                   /usr/include/iso/string_iso.h
         /opt/SUNWspro/prod/include/CC/Cstd/rw/string_ref
    If in particular you do not see /opt/SUNWspro/prod/include/CC/Cstd/./string, or if the "string" header marked above comes from some other location, something is definitely wrong with the compiler installation.
    If you see the correct string header, run "wc" on that header. You should see this:
    1858 6099 68105 string
    If not, the string header is corrupted.
    To re-install, refer to the Installation Guide that comes with Sun Studio 9. Follow the instructions for uninstalling Sun Studio 9. Then run the product installer, paying close attention to any warnings or error messages. I strongly recommend using the product installer, and not trying to install the product yourself directly from the packages.

  • How to use String Tokeniser inside this for loop?

    [i][i]hi there..
    i am reading all the file inside a directory and get the latest modified file than i have to tokenise it and juz read the number. For example my file name that is last modified will be abc_123.txt but i just want it to appear 123.
    i manage to do it separately how can i put the tokeniser inside my for loop?
    my directory
    for (int i = 0; i < files.length; i++)
                        if(files[i].isFile())
                             if(lastModifiedFile == null){
                             lastModifiedFile = files[i];
                             String mylastModifiedFile = lastModifiedFile.toString();
                             StringTokenizer tokens = new StringTokenizer (mylastModifiedFile,".");
                             String modified = tokens.nextToken().substring(modified.length-4);*/
                             if(lastModifiedFile != null)
                                  if(lastModifiedFile.lastModified() < files[i].lastModified())
                                       lastModifiedFile = files[i];
    my tokeniser is this
    String mylastModifiedFile = lastModifiedFile.toString();
                             StringTokenizer tokens = new StringTokenizer (mylastModifiedFile,".");
                             String modified = tokens.nextToken().substring(modified.length-4);*/
                   }

    [i][i][i]hi there..
    i am reading all the file inside a directory and get ...
    tokens.nextToken().substring(modified.length-4);*/
                   }[/i][i][/i][/i][/i]Is there some reason for this baroque formatting? Please use the
    code tags as explained in one of your other threads on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=793441&messageID=4510858#4510858

  • How to use string as an expression in SSRS reports

    Hello all,
    I have created a SSRS report in which I have used a tablix and a single dataset (ds_test)
    Now the dataset use t-sql and  is calling a table in which has data as shown below:
    What I am trying to do is to use this as an expression inside the cell of the tablix. But when I run the report It give me:
    But It should show the result as "True", I know it is taking this as a string but is there any way so that we can use this as an expression in the report
    NOTE: We cannot use this directly in report , because this is generated dynamically and should always present in DB tables only
    Thanks in advance
    Pankaj Kumar Yadav-

    So your table has a varchar column with 'iif(1=1,True,False)'  in one of the records ?
    yes
    Pankaj Kumar Yadav-
    You wont be able to pass a value from db like this and use this as an expression inside SSRS.
    If you're using SQL 2012 you can exec this expression using dynamic sql and then show return value as is in a SSRS report.
    SSRS is a presentation tool with limited scripts and it cant do any query processing against database. that part have to be implemented using t-sql query on backend (dataset)
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

Maybe you are looking for

  • Deactivate the automatic Creation of Delivery after Sales Order is Posted

    SD gurus, When I am creating a Sales Order, after posting it I want to create the delivery for the same manually. But the configuraion is so made that the delivery is automatically generated. How do i go for it ? Kindly help

  • InfoSet with more than one cube

    Has anyone created an infoset with more than one cube? Are there any hints for to pay attention? Regards Chäsitzer

  • Can I add a caller DURING a group call?

    I am aware that if someone calls me with Skype during a group call, I can bring them into the group right away by simply accepting their call.  However, how does one make it work in the other direction?  When I am on a group call, and the group decid

  • HT4759 How do I syn my calendars in Mavericks without using iCloud?

    I use a MiFi hotspot to access the internet. I HAD synched my devices via USB before I "updated" to Mavericks. I do not have an iCloud account. I have discovered that my calendars do not update when I connect to my MBpro.

  • Is there a way around the build-in FTP as read-only access

    "With read-only access, you can copy files from the server, but to copy files to the server you may need another FTP app. Choose Apple menu > App Store to find FTP apps available for OS X." Is there a way to get around this? Can i get the build-in FT