Removing \n and leading spaces with String.replaceAll()

I am trying to format a large XML string that contains carriage returns and lines with leading spaces. Something like this (pseudo example)...
s: "<a>
��<b>some text</b>
��<c>
����<d>more text</d>
��</c>
</a>"When i am done, i want it to look like this...
s: "<a><b>some text</b><c><d>more text</d></c></a>"I have tried using replaceAll() in this way....
  s = s.replaceAll("^\\s+","");// to remove leading spaces
  s = s.replaceAll("\\n","");// to remove carriage returnsHowever, I am not getting the results I expect. In fact, the entire string seems to simply turn into all whitespace....
s: "                                           "My question is: Is there an easier way? (or at least a way that works?)

try this:
public String transformXML(String s) {
    s = s.replace("^\\s+", "");
    s = s.replace("\\s+$", "");
    s = s.replace("\\s+", " ");
    s = s.replace("\\s*<\\s*([^<>]*?)\\s*>\\s*", "<$1>");
    return s;
}which would transform your example expression from:
<a>
<b>some text</b>
<c>
<d>more text</d>
</c>
</a>
to probably what you want:
<a><b>some text</b><c><d>more text</d></c></a>
Hope this helps~
Alex Lam S.L.

Similar Messages

  • Removing trailing and leading spaces

    How do I remove both leading and training spaces from a statement. SHIFT LEFT is working fine....but SHIFT w_text RIGHT DELETING TRAILING '*' does not seem to work in my code.
    The field value is ***ABCCDE*FGHI**JKL****
    and I want the o/p as ABC*CDE*FGHI***JKL
    Regards,
    Sameena

    Hi, Sam.
    Test Sample Code Bellow.
    Note: Variable Must be Type String not Character with Character Type SHIFT will not work Properly
    DATA: test TYPE string.
    test = '****ABC**CDE***FGHI****JKL*****'.
    SHIFT test LEFT DELETING LEADING '*'.
    SHIFT test RIGHT DELETING TRAILING '*'.
    CONDENSE: test.
    WRITE: test.
    Regards,
    Faisal

  • Trailing and Leading Spaces

    Hi we use file shares on a windows 2003 server for our storage for our macs. some of macs are 10.4 and some 10.5. We have a major problem in that when some of our windows users try and access these files they cant and even in some cases the files/folders disappear.
    After a lot of rooting around we found that the macs were creating these trailing spaces/leading spaces when they either accessed or created a folder on the windows share, please someone out there tell me there is something i can do to fix this and stop this from happening.
    cheers

    Hi,
    Purvesh K wrote:
    One another way using Regular Expressions!!!
    Assumes Alphabets or Numbers follow before and after the Space. If Special characters are to be included, query will have to be modified.This also assumes that the same column has to have both leading and training spaces. (Etbin's solution found rows where any column had either, not necessarily both, leading ad trailing spaces.)
    with data (col) as
    select 'first' from dual union all
    select 'first ' from dual union all
    select ' first ' from dual
    select *
    from data
    where regexp_like(col, '[[:space:]]+[[:alnum:]]+[[:space:]]+')
    COL  
    first Try adding
    select 'This has embedded spaces.' from dual union allto the sample data. The code above finds this row, even though it has neither leading nor trailing spaces.
    Remember that regular expressions are not anchored . The pattern can start and/or end anywhere in the string. In the example above, the substring ' has ' matches the pattern you gave. If you're using regular expressions, anchor them to the beginning and end of the string using ^ and $.
    So
    where regexp_like(col, '^[[:space:]].*[[:space:]]$')would be better. However, that would miss cols tha consisted of a single space. To include them:
    where regexp_like(col, '^[[:space:]](.*[[:space:]])?$')OP: If none of these solutons match your needs, then we don't understand your needs. Post a little sample data (CREATE TABLE and INSERT statements, or a WITH clause, like Purvesh used) and the results you want from that data.
    Regular expressions do wonderful things, but they don't do them very fast. If perfrmance is important, use TRIM (like Etbin suggested), or LIKE, or SUBSTR.

  • Trouble with String.replaceAll( )

    Hi,
    I have a string which contains instances of the backslash character followed by the double quote character and I'd like to replace those two characters with just a double quote. Or to put it slightly differently, I'd like to remove all backslash characters which precede double quotes. It seems like this should be straight-forward, but for some reason, I'm not getting the results I expect.
    Here is my code:
              String s1 = "Foo\\\"Bar";
              System.out.println("s1 = " + s1);
              int len = s1.length( );
              System.out.println("s1.length( ) = " + len);
              String s2 = s1.replaceAll("\\\"", "\"");
              System.out.println("s2 = " + s2);
              len = s2.length( );
              System.out.println("s2.length( ) = " + len);
    And here is the corresponding output:
    s1 = Foo\"Bar
    s1.length( ) = 8
    s2 = Foo\"Bar
    s2.length( ) = 8
    So, the string isn't being changed at all. What am I doing wrong? Thanks in advance for any replies.
    -ts1971

    Melanie_Green wrote:
    string.replaceAll()Takes two arguments, the first is a regular expression, the second is a String. Regular expressions have their own syntax compared to Strings, to match a single black slash in a regular expression you must write "\\\\".
    MelJust a little nit-pick: the second parameter is not a plain String but a "regex replacement String". In it, the following characters have a special meaning and therefore need to be escaped if you'd like to use them as literals:
    $    // used for match-group interpolation
    \    // used to escape '$' and '\' itself

  • -refurbished iMac has a 20GB partition for Boot Vamp with FAT format.  I want to remove this and replace it with a much bigger format with NTFS formats?

    My (new to me) Apple refurbished iMac has a 1TB hard drive. Running OS 10.6.7 Snow Leopard.  When I tried to install a Boot Camp partition, prior to installling Windows 7- 64 bit, I discovered that the machine had a 20 GB Boot Camp partition, too small for what I need.  HOw do I remove the 20 GB partition, and replace it with a 500 GB partition?

    I have a number of PC and Mac Pro running Windows Pro, and the OS only needs 80GB partition, plus whatever data etc.
    New but used does not sound like Apple Store (refurbished) Specials which would be a 'virgin' OS.
    I would reformat and do your own clean install.
    There may be something wrong and why it was left that way for one thing. May be a problem with the partition table.
    Boot from OS X DVD and you can usually try Disk Utility to "-" remove and then repair and get back, and you of course normally should be able to just use Boot Camp Assistant which is one of its functions - not just to create partition.
    For normal resizing, or creating the free space you need has to be in one contiguous chunk and not be fragmented, which is hard to imagine that 500GB is going to be intact.
    And whatever you do, rule #1 in the pdf guide: backup before beginning.
    http://www.apple.com/support/bootcamp

  • Question about minimizing. why ddid apple remove minimizing and replace it with NOTHING?

    on tiger, i could double click in the "gray bar" on top of every window in order to minimize it. this was a very good idea, since the buttons to minimize, close or maximize are very small and i also tend to activate my upper left hot corner when moving my cursor to the buttons....
    i think it's good to always change stuff. but if apple removes a function to replace it with nothing at all, i just don't get the point of removing it, since it was a good idea. i know: less is more! but i don't think it's meant this way

    They didn't remove it. You just don't know where to turn it on. The "gray bar" is called the title bar.
    General System Preferences:

  • How to remove fields and the space the occupy form a form before printing

    I have a dynamic form which should only print certain portions depending on checkboxes (if checkbox is checked, print paragraph; otherwise, don't print). I am using javascript to change the paragraph form visible to hidden prior to printing. I would like to also eliminate the blank space when I make the paragraph hidden. In other words, I want to collapse the pdf document based on the user inputted check boxes. Anybody have a simple solution? I am using LiveCycle Designer 7.1.

    The paragraph that you want to hide, and the object below it, need to be contained in a subform that is set to Content: Flowed.  This will allow everything inside that subform to move up when an object is hidden.  If you set the Content of a subform to Positioned, it will place objects at the exact position that you specify when you design the form, regardless of whether other objects are visible or hidden.

  • I have an iphone 3GS while on itunes it asked me if I wanted an update,it downloaded and then asked me if I wanted to remove my old data to replace it with the new.I agreed and it removed everything and left me with nothing all.What to do??

    How do I get my data back off my computer into my iphone?And how do I find it?I'm technologically deficient!!

    Restore from the backup created when the upgrade took place.  This should have been part of the upgrade process.
    Did the upgrade actually complete?
    Sounds like you simply restored as "new" when you should have been restoring from your backup.

  • Using an imac. Only the top fifth of the firefox homepage appears on screen. Have removed program and reloaded but with same result

    Have been using Firefox for some time on an imac. Appproxiamtely three weeks ago, opened it and got only about the top fifth of the home page and no functionality. Have unloaded/deleted the program and reloaded it but get exactly the same appearance (which was themed so I know it is the same). Cannot delete it further, new downloads do not replace it. Unusable

    Your user agent in the More system details list shows that you have the Firefox 3.6.15 version
    *Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-GB; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15
    Where do you see "3.6.13" ?

  • Removing leading spaces in smartforms

    When I print numbers in smartforms, they usually have a bunch of leading spaces, which messes up the formatting. E.g. a CURR 15 field containing 5000 will print as "          5.000,00".
    I saw the formatting options in the BC470 manual but there are only options to remove leading zeros, or to replace leading spaces with a Filler. What I need is to remove the leading spaces. Anyone know how?
    For the moment I'm copying all the numbers I want to print to string fields and using CONDENSE on those, but then I don't get the right number formatting, e.g. I get "5000.00" while I need "5.000,00".

    Hi
    The format of amount field depends on the currency key, the smartforms should write the amount in right format if it can understand which currency is to be used.
    The link between these field is done in the dictionary.
    If the samrtform can't understand it you can move the amount in the char field using WRITE statament and print this field instead of original one:
    WRITE <AMOUNT> CURRENCY <CURRENCY> TO CHAR_AMOUNT.
    Max

  • Removing a 2003 DC and replacing it with 2008R2 DC

    hi all. 
    i have been doing a lot of reading and think i know the correct process, i just wanted to double check with the community.
    we have 2 DC's in our environment DC1 and DC2 
    DC1 is 2008r2 and hosts ADDS/DNS/DHCP/GC and all FSMO roles
    DC2 is 2003 and hosts ADDS/DNS/GC and is there for redundancy
    DC2 is a bit on the old side and i would like to remove it and replace it with a newer 2008r2 DC, from what i have read it seems the best process for this would be to run DCPROMO from DC2 and demote it and remove then promote a new server
    DC3 is the server in waiting so running DCPROMO to promote it to a DC and allow replication to do its stuff and job done.
    are there any steps that i am missing?
    cheers
    Gordon

    Hello,
    I wouldn't care with the naming/numbering. So run dcpromo for DC3, make it DNS/GC and if this machine has complete replicated an you have checked everything with the support tools start with demoting DC2.
    That way you still have redundancy and can check BEFORE removing the old DC.
    Assure that the new machine has also the SYSVOL/NETLOGON share after promotion. I recommend that you use ONLY DC1 as DNS server on the NIC from DC3 and NONE else. Later on you can change the DNS server settings.
    The support tools can be used to create output files:
    dcdiag /v /c /d /e /s:dcname >c:\dcdiag.log
    repadmin /showrepl dc* /verbose /all /intersite >c:\repl.log  ["dc* is a place holder for the starting name of the DCs if they all begin the same (if more then one DC exists)]
    dnslint /ad /s "DCipaddress" (http://support.microsoft.com/kb/321045)
    ADREPLSTATUS
    http://www.microsoft.com/en-us/download/details.aspx?id=30005 can also be exported to file.
    Best regards
    Meinolf Weber
    MVP, MCP, MCTS
    Microsoft MVP - Directory Services
    My Blog: http://blogs.msmvps.com/MWeber
    Disclaimer: This posting is provided AS IS with no warranties or guarantees and confers no rights.
    Twitter:  

  • Matcher vs. String.replaceAll

    I have been experiencing a problem attempting to use an expression such as:
    s = s.replaceAll("PATTERN","REPLACEMENT");
    to replace certain regular expressions in a document. When using the Matcher to replace Strings as follows there is no problem, but using the same pattern with String.replaceAll doesn't seem to perform the replacement.
    Pattern pattern = Pattern.compile("PATTERN",Pattern.DOTALL);
    Matcher matcher = pattern.matcher(s);
    s = matcher.replaceAll("REPLACEMENT");
    The only thing I can think of is that the Pattern.DOTALL options allows the match to take succeed, where it wouldn't otherwise. Therefore I was wondering if there an equivalent for the String.replaceAll method perhaps? Any ideas?
    Thanks very much,
    Ross Butler

    I'm having trouble believing that PATTERN and REPLACEMENT are the real string you're using, but it's probably not important, since it sounds like you probably diagnosed the problem yourself.
    According to the Javadocs, replaceAll gives the same result as Pattern.compile(regex).matcher(str).replaceAll(repl), but obviously that wouldn't necessarily be true if you add extra parameters somewhere in there, so I would say that replaceAll is more of a convenience method that you use when you don't need any extra parameters.
    However, if you need to use DOTALL or something else similar, you'll need the longer way using Matcher.
    That shouldn't stop you from writing your own convenience method, though. :)

  • Bug in String.replaceAll()

    Hi folks,
    Have anybody try to do the following with String.replaceAll()?
    String path = "/ssss/ssss/sssss/";
    path.replaceAll("/", "\\");
    It will throw IndexOutOfBoundException.
    Billy Ng

    I'm not sure that's a bug, it's just the behavior of the underlying regex processor.
    Regardless, to get the effect you want, try:
    String path = "/ssss/ssss/sssss/";
    path.replaceAll("/", "\\\\");

  • Removing leading zeros and leading blank spaces from an input field

    Hi All,
    I have an input field which is alphanumeric and i need to remove the leading zeros and blank spaces in it , but intermediate spaces should be kept .
    so i used the UDF
            String output = input.replaceFirst("^0+","");
            return output;
    but this code does not remove the leading blank spaces . Can anybody help in modifying this code so that even the leading blank spaces along with leading zeros  can be removed .
    Regards ,
    Loveena .

    lets say input is a
    then
    int len = a.length();
    for(int i;i< length;i++)
    if(a.substring(0,1).equals(" ") || a.substring(0,1).equals("0"))
    a = a.substring(1,len);
    return a;
    hope you got the logic so that you can enhance it better

  • Removing leading spaces in a decimal number

    I have a decimal number field of length 28 with 9 spaces.I have to print it right justified and remove the leading spaces.I appreciate if anyone can let me the statement for this

    Hi,
      Try this..
    DATA: V_P TYPE P DECIMALS 2.
    V_P = '112.00'.
    WRITE: / V_P.
    DATA: STR TYPE STRING.
    STR = V_P.
    SHIFT STR LEFT DELETING LEADING SPACE.
    WRITE: / STR.
    Thanks,
    Naren

Maybe you are looking for