How to eliminate "\n" using String.replaceAll(str, str)

I've noticed a few people having prob with replaceAll in the forum.
Here's what I want to accomplish.
I need to put the value received from HTML <textarea>, into just one line in a file.
String sentence = "line1\nline2\nline3\nline4\n";
System.out.println("before" + sentence);
System.out.println("after" + sentence.replaceAll("\n", "\\n");The result looks like this.
before= line1
line2
line3
line4
after= line1nline2nline3nline4n
Notice that a backslash is missing.
How can I get the original string with "\n" placed at the right place??
Thanks a lot.
Masako

I've noticed a few people having prob with replaceAll
in the forum.
Here's what I want to accomplish.
I need to put the value received from HTML <textarea>,
into just one line in a file.
String sentence = "line1\nline2\nline3\nline4\n";
System.out.println("before" + sentence);
System.out.println("after" + sentence.replaceAll("\n",
"\\n");The result looks like this.
before= line1
line2
line3
line4
after= line1nline2nline3nline4n
Notice that a backslash is missing.
How can I get the original string with "\n" placed at
the right place??
Thanks a lot.
Masako
I got the results you were looking for by doing it this way:
sentence.replaceAll("\\n", "\\\\n");I'm a bit confused about this result, though. Like someone said earlier, i thought "\n" was a single character. Maybe it doesn't get evaluated into the newline character until it's displayed...?

Similar Messages

  • 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);
    }

  • String.replaceAll bottleneck

    Hi All,
    I have written a method to make a string "safe" for xml, by encoding characters that need to be replaced.
    It works just fine using String.replaceAll as below, but when i profile the app i see that it is a performance bottleneck.
    I can see that it is creating a lot of Strings so this is part of the problem.
    From reading through the forum I can see regexs used frequently for this type of problem, but it seems that they will not be more efficient than my existing approach.
    I see that StringBuffer has a replace method but i'm not sure that it is a good fit for my problem?
    Can anybody suggest a more efficient solution?
    Your help is much appreciated!
    emhart
    Here's my existing method:
    public static String makeSafeForXML(String str)
    String result = str;
    result = result.replaceAll("&", "&");
    result = result .replaceAll(">", ">");
    result = result .replaceAll("<", "<");
    result = result .replaceAll("'", "&apos;");
    result = result .replaceAll("\"", """);
    return result ;
    }

    That method doesn't make any sense to me:
    replacing strings with the same exact string?
    also the last one isn't correct, maybe missing a \ ?
    Also, you do realize that the replaceAll method uses the first argument as a regex to match patterns in the string?
    My apologies if I'm missing something.
    But if this really is what you want, then maybe this is faster (I haven't measured any times though):public static String makeSafeForXML2(String str)
        StringBuilder sb = new StringBuilder(str);
        for (int i = 0; i < sb.length(); i++) {
            switch (sb.charAt(i)) {
                case '&':
                    sb.replace(i, i + 1, "&");
                    break;
                case '>':
                    sb.replace(i, i + 1, ">");
                    break;
                case '<':
                    sb.replace(i, i + 1, "<");
                    break;
                case '\'':
                    sb.replace(i, i + 1, "'");
                    break;
                case '"':
                    sb.replace(i, i + 1, "\"");
                    break;
        return sb.toString();
    }

  • String.replaceAll problem

    I need to replace a single quote ( ' ) in a string with two single quotes. I am trying to use String.replaceAll method but it does not work. I guess my regular expression is not correct. I have tried several combinations already.
    text.replaceAll(".'.","''");
    text.replaceAll("'","''");
    text.replaceAll("\\'","''"); None of them have worked. It does not change the text as I'd like it to.

    It's been at least a week since I've posted this:
    Since regex patterns are involved, you can use the simpler replace method:
    str = str.replace("'", "''");By the way, I hope you not doing this to insert text into a database!

  • When I forward an e-mail, I get a long string of gobblygook that goes with it and I cannot figure out how to eliminate it without having to delete it every time

    When I forward an e-mail, I get a long string of gobblygook that goes with it and I cannot figure out how to eliminate it without having to delete it every time I forward an e-mail. The following is only part of the string that I am talking about. How can I eliminate this from the e-mail?
    Here is part of an excerpt from one of the strings:
    From: - Mon Aug 19 18:12:47 2013
    X-Account-Key: account1
    X-UIDL: 065B31352CC6B3C0789DEA7954395B55
    X-Mozilla-Status: 0001
    X-Mozilla-Status2: 00000000
    X-Mozilla-Keys:
    Return-Path: <[email protected]>
    Received: from hrndva-mxlb.mail.rr.com ([10.128.255.126]) by hrndva-imta07.mail.rr.com with ESMTP id <20130819211326470.DBUO12525@hrndva-X-Roving-StreamId: 0

    Sorry, Firefox doesn't do email, it's strictly a web browser.
    If you are using Firefox to access your mail, you are using "web-mail". You need to seek support from your service provider or a forum for that service.
    If your problem is with Mozilla Thunderbird, see this forum for support.
    [https://support.mozillamessaging.com/en-US/home] <br />
    or this one <br />
    [http://forums.mozillazine.org/viewforum.php?f=39]

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • How do I convert a string, and use a string as a property?

    I have an array in the following format:
    {ownsCar: 'true', ownsBike: 'true', ownsHouse: 'true'}
    {ownsCar: 'false', ownsBike: 'true', ownsHouse: 'true'}
    {ownsCar: 'true', ownsBike: 'false', ownsHouse: 'true'}
    etc ............
    And I need to test against each item e.g.
    if...
    myDataGrid[myItem].ownsCar == Object(myCheckbox).label
    ... then
    if...
    myDataGrid[myItem].ownsBike == Object(myCheckbox).label
    ... then
    if...
    myDataGrid[myItem].ownsHouse == Object(myCheckbox).label
    ... then
    But I need to build my application where the property (e.g. "ownsCar", "ownsBike", "ownsHouse") is a variable such as:
    if...
    myDataGrid[myItem].myProperty == Object(myCheckbox).label
    ... then
    I would like to loop through my Array, counting the number of items, and then use each item as a property.
    How would I convert the string (e.g. "ownsCar") into a property "myProperty" ???
    Many thanks in advance
    Chris

    Thanks, but my problem is that I won't know what my property will be.
    E.g. they could be...
    {svnsdkvnsdklvnsdklv: 'true', seuAfnwfnw: 'true', asfwseionf: 'true', etc.................}
    and there could be lots of them.
    I need to have myObject[N], where N is a variable property for each of the items taken from a variable length array
    so...
    ownsCar is represented by myObject.[N]
    ownsHouse is represented by myObject.[N+1]
    ownsBike is represented by myObject.[N+2]
    etc
    (sorry, this is so difficult to explain when I dont know what the answer is)

  • How to search for upper/lower case using string using JAVA!!!?

    -I am trying to write a program that will examine each letter in the string and count how many time the upper-case letter 'E' appears, and how many times the lower-case letter 'e' appears.
    -I also have to use a JOptionPane.showMessageDialog() to tell the user how many upper and lower case e's were in the string.
    -This will be repeated until the user types the word "Stop". 
    please help if you can
    what i have so far:
    [code]
    public class Project0 {
    public static void main(String[] args) {
      String[] uppercase = {'E'};
      String[] lowercase = {'e'};
      String isOrIsNot, inputWord;
      while (true) {
       // This line asks the user for input by popping out a single window
       // with text input
       inputWord = JOptionPane.showInputDialog(null, "Please enter a sentence");
       if ( inputWord.equals("stop") )
        System.exit(0);
       // if the inputWord is contained within uppercase or
       // lowercase return true
       if (wordIsThere(inputWord, lowercase))
        isOrIsNot = "Number of lower case e's: ";
       if (wordIsThere(inputword, uppercase))
         isOrIsNot = "number of upper case e's: ";
       // Output to a JOptionPane window whether the word is on the list or not
       JOptionPane.showMessageDialog(null, "The word " + inputWord + " " + isOrIsNot + " on the list.");
    } //main
    public static boolean wordIsThere(String findMe, String[] theList) {
      for (int i=0; i<theList.length; ++i) {
       if (findMe.equals(theList[i])) return true;
      return false;
    } // wordIsThere
    } // class Lab4Program1
    [/code]

    So what is your question? Do you get any errors? If so, post them. What doesn't work?
    And crossposted: how to search for upper/lower case using string using JAVA!!!?

  • How to get substring from string using index?

    hi,
    here i am having string ,
    i want the pullareddy from below line ,
    i know how to get from substring.
    but i want to get the above using "index",
    can any help how to do it?
    String str1="janapana,pullareddy, in malaysia";
    jpullareddy

    get the start index with indexAt("pullareddy")
    get the end index with adding the length of the word to the start
    get the char[] of str1 with toCharArray()
    make a new string with the chars from start to end index.

  • How to create dynamic connection string with variables using ssis.

    Hello,
    Can anyone let me know on how to create dynamic connection string with variables using ssis?
    Any help would be appreciated.

    Hi vinay9738,
    According to your description, you want to connect multiple database from multiple servers using dynamic connection.
    If in this case, we can create a Table in our local database (whatever DB we want) and load all the connection strings.  We can use Execute SQL Task to query all the connection strings and store the result-set in a variable of object type in SSIS package.
    Then use ForEach Loop container to shred the content of the object variable and iterate through each of the connection strings. And then Place an Execute SQL task inside ForEach Loop container with the SQL statements we have to run in all the DB instances. 
    For more details, please refer to the following blog:
    http://sql-developers.blogspot.kr/2010/07/dynamic-database-connection-using-ssis.html
    If there are any other questions, please feel free to let me know.
    Regards,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • String.replaceAll howto use it ?

    Hi everyone I want to replace newlines in a String with spaces. I though the use of replaceAll would be great but am having no luck with it at all.
    String commentString "hello\nhello\n";
    commentString.replaceAll("\\\n", " ");
    I have no idea why this is not working, any help appreciated.
    Cheers
    Dan

    public class Test {
        public static void main (String[] parameters) {
            System.out.println ("a\nb".replaceAll ("\\n", " "));
    }Kind regards,
      Levi

  • How can i extract data strings (temp. press. rel.hum etc) using a Virtual interface through an RS-232 connection​?

    How can i extract data strings (temperature, pressure, relative humidity etc) using a Virtual interface through an RS-232 connection?

    Try this.  It is in LV 8.5.
    Note the double % in the format string.  This is so the % in the input string is treated as a percent rather than a code.
    You may also have to work with the line feed characters in case they are different in the string coming in compared to how the string shows up in the web browser.
    Message Edited by Ravens Fan on 02-12-2008 10:19 PM
    Attachments:
    Example_BD.png ‏4 KB
    Untitled 11.vi ‏9 KB

  • 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 eliminate the extra line in the emaildody while using EMAIL_PLAIu200BN

    Hi Experts,
    I am using EMAIL_PLAIN option for extended notifications via SWNCONFIG. In the body of the email a horizantal line is getting displayed on the top of the email body. How to eliminate this line??
    Thanks and Regards
    Srini..

    Hi,
    In tcode SE80, select BSP Application and put SWN_MESSAGE1 in text field. So, you can see plain_indiv and plain_multi HTML. If you click-on this you can see the layout and the standard horizontal line.
    If you want to change it, you have to copy this BSP and create a Z one and change the layout. Now, in tcode SWNCONFIG, go to Message Template and change BSP-URL.
    Regards,

Maybe you are looking for

  • Split Cost centre - PO Commitment

    Hi , I have a SC - PO with multi account assignment ( 50 % split on 2 cost centres) , this was raised by mistake and i want to Delete the PO to put the commitment back .I can't delete the PO in the back end based on the deployment scenario.I have don

  • No internet - self assigned ip problem?

    I have an Intel imac (OSX leopard, 10.5.8 )and an ethernet modem connected direct to it. The lights are on as usual on the modem but i cannot get the internet. When I look at the ethernet status in network in system preferences it says I have a 'self

  • No green checkmark after signing pdf document in acrobat reader x

    I have signed about multiple pdf docs but dont know why the green check mark is not appearing the certificate show that it is valid.My clients are not accepting this as there is no green check mark.I have added all the digital signatures to trusted i

  • Trust and Key Store config values? - OBPM 10g (Linux) With Websphere6 (AIX)

    HI, We installed OBPM 10gR3 on Linux (10.3.2 for Websphere) with Websphere 6.1.0.21 on AIX, When we try to save values in following section we are getting an error: Engines > Edit Engine bpmengine > JMX Engine Management Configuration Attributes are:

  • Populate sequence of dates on iPad?

    I built a form that uses javascript to populate two weeks of dates based on the date a user enters. People using an iPad have problems because javascript isn't enabled. Apart from lowering security on their iPad is there a way to populate dates on a