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

Similar Messages

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

  • Replace function - special characters

    Hi All,
           If my column is encountering special characters I would like to replace with blank. Special characters may vary from record to record. Sometimes it is @ sometimes $,!,,$,^,<,&,<,>,?,",{,},+,_,),(.
    Do we have any function same like replace that can replace all special characters, whatever it encounters with required value?
    - please mark correct answers

    Take a look at this article
    T-SQL:
    How to Find Rows with Bad Characters
    and check See Also section in that article for more articles on that topic.
    For every expert, there is an equal and opposite expert. - Becker's Law
    My blog
    My TechNet articles
    Thanks Naomi
    - please mark correct answers

  • Need help in replacing special characters in a string

    Hi,
    please let me know the best way to replace all the special characters in a string with space.
    other than alphabets and numbers
    with regards.
    sumanth.

    please let me know the best way to replace all the special characters in a string with space.
    other than alphabets and numbers
    >
    Sumanth Nag Kristam wrote:
    > actually i need to replace hexa decimal char 0X1A in a string.... that is 'substitue' as per the chart
    > any pointers....
    >
    > chk the link for the ASCII codes
    > http://www.techonthenet.com/ascii/chart.php
    But in Hexa decimal value there is no special characters?

  • Finding special characters in a string

    Hi all, I'm using Oracle 10g.
    I have a column name with special characters. how can i replace the special characters in the column with space and no space depending on the special character. please see the example below. can i use REGEXP_REPLACE?
    create table
    create table sample_test (
      Name    VARCHAR2(20 BYTE))insert table
    insert into sample_test values ('O''NEIL')
         insert into sample_test values ('B.E.VICTOR')
          insert into sample_test values ('WILLIAM,L')
           insert into sample_test values ('MARY-ANNE')
               insert into sample_test values ('VON_ANCKEN')
                insert into sample_test values ('BROWN;L')i would like the output as follows
    Special Character         Name         Expected Name                  Remarks     
    Single Quotes            O'NEIL                  ONEIL                          Remove quotes and no space       
    Dot                      B.E.VICTOR         B E VICTOR                          Replace with space       
    Comma                      WILLIAM,L         WILLIAM L                          Replace with space       
    Hyphen                      MARY-ANNE         MARY ANNE                          Replace with space       
    Underscore                VON_ANCKEN         VON ANCKEN                          Replace with space       
    Semi Colon              BROWN;L          BROWN L                          Replace with space      Please advise.
    Thanks
    Bob

    A simple solution without regexp usage:
    -- Test Data
    with sample_test as
    select 'O''NEIL' name from dual union all
    select 'B.E.VICTOR'  name from dual union all
    select'WILLIAM,L' name from dual union all
    select'MARY-ANNE' name from dual union all
    select'VON_ANCKEN' name from dual union all
    select'BROWN;L' name from dual
    -- Query:
    select name old_name,
           translate(replace(name,'''',''),'.,-_;','     ') new_name
    from sample_test;Explanation:
    REPLACE deletes the quote
    TRANSLATE replaces dot, comma, hyphen, semicolon and underscore

  • Replace Special Characters in a string + XQUERY

    Hi All,
    I am using the following replace function to replace the special characters in my XQUERY.
    *replace($string1, '[&"-*;-`!|:,¿/{}@#$%^*~()_+-]', ' ')*
    Fortunately it is replacing all the special characters. But the only problem here is it is even replacing capitol letters in to spaces, which I don't want.
    Please help me out!!

    Hi
    <<< What did u change >?> I dont see any change with the Regex ?  >>
    if you observe in the modified function, he just removed (*) inside the replace funtion.
    Thanks
    Shankar AUNV

  • RegExp for excluding special characters in a string.

    Hi All,
    Im using Flex RegExpValidator. Can anyone suggest me the correct expression to validate this condition?....
    I have tried this expression :----- /^[^///\/</>/?/*&]+$/...But in this it is also negating the alphabets.Also I have tried with opposite condition that in the String we should have alphabets and the expression is:-- ([a-z]|[A-Z]|[0-9]|[ ]|[-]|[_])*..... Please can anyone help me on this.
    Thanks in advanced to all.
    Munira

    sorry but you are posting things back that do not make any sense
    what do you mean with the below comment?
    munira06 wrote:
    Yes you are correct ,but I have tried this with single special character
    say
    Re: RegExp for excluding special characters in a string.
    here is a sample app taken from the live docs
    using ^[a-zA-Z0-9 \-_]*$ as the regex accepts all characters from a-z, A-Z, 0-9 - [space] and_
    run the example tell me what regex you are using and what test strings fail when they should pass or pass when they should fail
    <?xml version="1.0" encoding="utf-8"?>
    <!-- Simple example to demonstrate the RegExpValidator. -->
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
            xmlns:s="library://ns.adobe.com/flex/spark"
            xmlns:mx="library://ns.adobe.com/flex/mx">
        <fx:Script>
            <![CDATA[
                import mx.events.ValidationResultEvent;
                import mx.validators.*;
                // Write the results to the
                private function handleResult(eventObj:ValidationResultEvent):void {
                    if (eventObj.type == ValidationResultEvent.VALID) {
                        // For valid events, the results Array contains
                        // RegExpValidationResult objects.
                        var xResult:RegExpValidationResult;
                        reResults.text = "";
                        for (var i:uint = 0; i < eventObj.results.length; i++) {
                            xResult = eventObj.results[i];
                            reResults.text=reResults.text + xResult.matchedIndex + " " + xResult.matchedString + "\n";
                    } else {
                        reResults.text = "";
            ]]>
        </fx:Script>
        <fx:Declarations>
            <mx:RegExpValidator id="regExpV"
                    source="{regex_text}" property="text"
                    flags="g" expression="{regex.text}"
                    valid="handleResult(event)"
                    invalid="handleResult(event)"
                    trigger="{myButton}"
                    triggerEvent="click"/>
        </fx:Declarations>
        <s:Panel title="RegExpValidator Example"
                width="75%" height="75%"
                horizontalCenter="0" verticalCenter="0">
            <s:VGroup left="10" right="10" top="10" bottom="10">
                <s:Label width="100%" text="Instructions:"/>
                <s:Label width="100%" text="1. Enter text to search. By default, enter  a string containing the letters ABC in sequence followed by any digit."/>
                <s:Label width="100%" text="2. Enter the regular expression. By default, enter ABC\d."/>
                <s:Label width="100%" text="3. Click the Button control to trigger the validation."/>
                <s:Label width="100%" text="4. The results show the index in the text where the matching pattern begins, and the matching pattern. "/>
                <mx:Form>
                    <mx:FormItem label="Enter text:">
                        <s:TextInput id="regex_text" text="xxxxABC4xxx" width="100%"/>
                    </mx:FormItem>
                    <mx:FormItem label="Enter regular expression:">
                        <s:TextInput id="regex" text="ABC\d" width="100%"/>
                    </mx:FormItem>
                    <mx:FormItem label="Results:">
                        <s:TextInput id="reResults" width="100%"/>
                    </mx:FormItem>
                    <mx:FormItem >
                        <s:Button id="myButton" label="Validate"/>
                    </mx:FormItem>
                </mx:Form>
            </s:VGroup>
        </s:Panel>
    </s:Application>

  • Find All Special Characters in a SQL Server

    I would like to find all Special Characters in a table. I am currently using the code below. Not sure if this gets all of them.
    select  top 50 *
    from [dbo].[SV20150122]
    where street LIKE '%[^0-9a-zA-Z @\.\-]%'
    SQL

    Depends on what you want to count as a special character.  Depending on your collation, your query might not consider é (for example) as a special character.  The same goes for other accented letters.  If that's what you want, then fine. 
    If that is not what you want, you may want to do
    where street LIKE '%[^0-9a-zA-Z @\.\-]%' Collate Latin1_General_BIN
    In any case, you can see exactly which characters are NOT counted as special characters on your system (with and without the Collate clause) by running
    Declare @Test Table(ID int, MyData char(1));
    ;With cte As
    (Select 0 As Number
    Union All
    Select Number + 1
    From cte
    Where Number < 255)
    Insert @Test(ID, MyData)
    Select Number, CHAR(Number)
    From cte Option(MaxRecursion 256);
    Select ID, MyData From @Test
    Except
    Select ID, MyData From @Test
    Where MyData LIKE '%[^0-9a-zA-Z @\.\-]%'
    Select ID, MyData From @Test
    Except
    Select ID, MyData From @Test
    Where MyData LIKE '%[^0-9a-zA-Z @\.\-]%' Collate Latin1_General_BIN
    Note: the above code assumes the column street is char or varchar. 
    Tom

  • DUMP: replace all occurrences of space in string1 with string2.

    Why does this statement results in a dump:
    replace all occurrences of space in string1 with string2.
    same with
    replace all occurrences of ' ' in string1 with string2.
    string2 is a string without spaces!
    Is there any drawback on using this statements as a workaround?
    while sy-subrc eq 0.
      replace space with string2 into string1.
    endwhile.
    Thanks
    norbert

    Hi,
    See this example i got from ABAPDOCU
    replacing values
    DATA: t4(10) TYPE c VALUE 'abcdefghij',
          string4 LIKE t4,
          str41(4) TYPE c VALUE 'cdef',
          str42(4) TYPE c VALUE 'klmn',
          str43(2) TYPE c VALUE 'kl',
          str44(6) TYPE c VALUE 'klmnop',
          len4 TYPE i VALUE 2.
    string4 = t4.
    WRITE string4.
    REPLACE str41 WITH str42 INTO string4.
    WRITE / string4.
    string4 = t4.
    REPLACE str41 WITH str42 INTO string4 LENGTH len4.
    WRITE / string4.
    string4 = t4.
    REPLACE str41 WITH str43 INTO string4.
    WRITE / string4.
    string4 = t4.
    REPLACE str41 WITH str44 INTO string4.
    WRITE / string4.
    SKIP.
    ULINE.
    Example for condensing strings
    DATA: string9(25) TYPE c VALUE ' one  two   three    four',
          len9 TYPE i.
    len9 = strlen( string9 ).
    WRITE: string9, '!'.
    WRITE: / 'Length: ', len9.
    CONDENSE string9.
    len9 = strlen( string9 ).
    WRITE: string9, '!'.
    WRITE: / 'Length: ', len9.
    CONDENSE string9 NO-GAPS.
    len9 = strlen( string9 ).
    WRITE: string9, '!'.
    WRITE: / 'Length: ', len9.
    SKIP.
    ULINE.
    Thanks & Regards,
    Judith.

  • Sample code to identify special characters in a string

    Hi,
    I need to identify special characters in a string.... could anybody send me some code please.......
    Thanks,
    Best regards,
    Karen

    data: str(100) type c.
    data: str_n type string.
    data: str_c type string.
    data: len type i.
    data: ofst type i.
    str = '#ABCD%'.
    len = strlen( str ).
    do.
      if ofst = len.
        exit.
      endif.
      if str+ofst(1) co sy-abcde.
        concatenate str_c str+ofst(1) into str_c.
      else.
        concatenate str_n str+ofst(1) into str_n.
      endif.
      ofst = ofst + 1.
    enddo.
    write:/ str.
    write:/ str_c.
    write:/ 'spacial chracter',20 str_n.
    Function module  <b>SF_SPECIALCHAR_DELETE</b> <b>DX_SEARCH_STRING</b>
    l_address1 = i_adrc-street.
    CHECK NOT L_ADDRESS1 IS INITIAL.
    len = STRLEN( l_address1 ).
    do len times.
    if not l_address1+l(1) ca
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '.
    if i_adrc-street+l(1) CO sy-abcde.
    elseif i_adrc-street+l(1) CO L_NUMCHAR.
    exit.
    endif.
    l = l + 1.
    enddo.
    data : spchar(40) type c value '~!@#$$%^&()?...'etc.
    data :gv_char .
    data:inp(20) type c.
    take the string length .
    len = strlen (i/p).
    do len times
    MOVE FNAME+T(1) TO GV_CHAR.
    IF gv_char CA spchar.
    MOVE fnameT(1) TO inp2T(1).
    ENDIF.
    T = T + 1.
    enddo.
    REPORT ZEX4 .
    PARAMETERS: fname LIKE rlgrap-filename .
    DATA: len TYPE i,
    T TYPE I VALUE 0,
    inp(20) TYPE C,
    inp1(20) type c,
    inp2(20) type c,
    inp3(20) type c.
    DATA :gv_char.
    data : spchar(20) type c value '#$%^&*()_+`~'.
    START-OF-SELECTION.
    CONDENSE fname.
    len = strlen( fname ).
    WRITE:/ len.
    DO len TIMES.
    MOVE FNAME+T(1) TO GV_CHAR.
    IF gv_char ca spchar.
    MOVE fnameT(1) TO inpT(1).
    ENDIF.
    T = T + 1.
    ENDDO.
    CONDENSE INP.
    write:/ 'Special Characters :', inp.
    Rewards if useful..........
    Minal

  • Replacing all occurrences of characters in a string with one new character?

    Hi there,
    I'm looking for a way that I could replace all occurrences of a set of specific characters with just one new character for each occurrence.
    For example if I have a string which is "word1...word2.......word3....word4............word5" how would I be able to replace this with just one character such as ":" for each set of "." so that it would essentially appear like this "word1:word2:word3:word4:word5"
    If I just use replace(".", ":") I am left with "word1:::word2:::::::word4::::word5::::::::::::"
    So therefore I'm guessing this would require the use of replaceAll() maybe? but I'm not really very familiar with how regular expressions work and how this would be accomplished using them.
    Any help would be greatly appreciated :) Thanks.

    Yes, but "." means any character, so ".\+" means "any character repeated more than once". If you just mean a full stop ("period" for you Americans :p) you should use "\.+" as your regular expression, but remember that for Java you need a '\' escape to recognise '\' as '\', so in code you'd actually type your regex as:
    "\\.+"Here's an example of one way to do it:
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Test {
        public static void main(String[] args) {
           String string = "example1.......example2...example3.....example4";
         Pattern pattern = Pattern.compile("\\.+");
         Matcher stringMatcher = pattern.matcher(string);
         string = stringMatcher.replaceAll(":");
         System.out.println(string);
    }Edited by: JohnGraham on Oct 24, 2008 5:19 AM
    Edited by: JohnGraham on Oct 24, 2008 5:22 AM

  • How to replace string containing special characters by another string

    Hi all,
    I have to Search for a pattern and replace it by a substitute pattern [Eg: Replace methodOrig (a,b) with  SessTime = getSessionParameter(time);  methodNew(a,b,SessTime) ] in files.
    i tried this using replace(),but it din't work since string1 contains special characters.
    can anyone help me asap.
    thanks in advance.

    Double-post: http://forum.java.sun.com/thread.jspa?threadID=599211&tstart=0

  • Replace Special Characters in a String

    Let's say someone copies the folowing list and pastes it into a Javascript prompt box:
    302304
    305678
    245675
    How do I manipulate the string so it reads:
    302304 305678 245675
    In other words, how do I replace the manual line breaks in a string with spaces?
    Thanks!

    \r and \n are both \s characters.
    This is functionally equivalent to what you have...
    stringName = stringName.replace(/\s/g,' ');
    I highly recommend browsing this website (lots of useful info there):
    http://www.regular-expressions.info/
    Harbs

  • Use of special characters in Search String

    What is the use of special charaters like
    in the search string in the Find & Replace of ABAP editor ?
    I want to search for all strings starting with V which are followed by alphabets like
    VA
    VB...
    If I use V*, it also gives me results like
    V/R...
    Whether it is possible to specify such a condition?

    Hi,
    While giving ur search in FIND & REPLACE,
    use the match case or match whole word only..
    Then u will get search results only where the exact case of that variable is used..
    As per my knowledge there is no signification of special characters ,- : ; in the search string..
    Hope this helps...
    Cheers,
    Simha.

  • PDS - XML format, unable to read special characters in a string.

    Hi All,
    I've been using XML files to create my report with Oracle9i's new featue of PDS.
    Now, I'm unable to read a file if it contains '&' or '<' in the string. In fact, the xml file itself not able to crate a xml page in the browser, if these special characters are present.
    Is there any way to solve this problem ?
    I can't tell the users to remove &, < from the description data. Is there any way to workaround for this ?
    Thanks in advance,
    Satya.

    Hi Rohit and Rajesh
    Thanks for your reply.
    In fact, my problem is like this:
    I'll get data in .txt file and save that as a .xml file in the network before calling Oracle report ,which gets data from the .xml.
    The contents are like this:
    <Comapy name> Ford Motors UK & Europe</Company name>
    <Department> HR & Pensions</Depatrment>
    <Salary>Grad4 < 25000 </Salary>
    As per XML entity character representation, I need to replace '&' with '&amp;' and '<' with '<lt;'
    I'm wondering is there any other way to solve this problem as it is difficult to replace '<' and '>' generically.
    Honestly, I couldn't understand what Mr. Rajesh was trying to tell.
    'for & use & ( with semicolon at the end)'
    'for < use <'
    'for > use >'
    Can you shed some light on this ?
    Many thanks
    Satya.

Maybe you are looking for

  • How do I find books in Chinese?

    How do I find books in Chinese?

  • Os X mavericks download being weird

    my os x mavericks won't download, i will click install app on the app store and it will ask for my apple id sign in yadayada and it will supposedly load and the green install button will be clicked and then it will go back unclicked and won't downloa

  • Flash File(SWF) shows up 1/2 the time when in header.jsp of 8.1.4 Portal

    I've tried every way for publishing it the ways Flash says to do it (Javascript and no Javascript) no dice... I'll load the page and when I right click where it's suppsed to be it's not there... But when I hit back and the forward again in the browse

  • Http's GET & POST.

    I'm trying to write a program to transfer files over "https" using "GET" & "POST", but I do not know where to start from, like which java packages to use, sample programs etc. Any pointers would be most helpful. Thanks a lot in advance.

  • Java Iview runtime error at enterprise portal while accessing BW reports

    Hi Expaerts , We are facing an issue while navigating through one of the BW reports at Portal, as it is showing Java Iview run time errror. Earlier we had the issue of Webass engine restart, but after increasing the heap dump we are facing the issue