Replace a character in a string

Hi,
I've been tearing my hair out trying to do something very simple, replace a backslash character in a string with an underscore. I've searched online and discovered the -replace parameter which you would think would work fine but no, it seems to get in a
tizzy because the character I want to replace is a backslash and I get an error: "Invalid regualr expression pattern".
Here's what I have which produces the error:
$str = 'start\end'
$str = $str -replace '\','_'
Can someone tell me how to do this? I simply want to replace a backslash with an underscore.
thanks
Jamie
http://sqlblog.com/blogs/jamie_thomson/ |
@jamiet |
About me

sod's law. I spend half an hour trying to figure this out and then as soon as I post this thread I figure it. The following works:
$str = 'start\end'
$str = $str -replace '\\','_'
$str
http://sqlblog.com/blogs/jamie_thomson/ |
@jamiet |
About me
"-replace" requires a regular expression for each argument, which is why you needed to escape your backslash with another backslash.  If you use the replace() string method, you are not required to use regular expressions:
$str = $str.replace('\','_') will work exactly as you expect it to.

Similar Messages

  • Replacing a character in a string to another character

    hi,
    i need to write a function or procedure to replace the character of a string value suppose:
    l_error:= 'abcdefghijklmnop' is a string
    i need write a function or procedure to replace the character "c" to "z"
    that data in l_error is not in any table.
    thanks,
    AJ

    I want to Replace all the Existence of the word - "Test" in a string with "Test1" whereever a space exits before the word Test and someother alphabet after "Test" i.e. Test will be replaced with Test1 if a word starts with Test and contains more alphabets also. For example - TestName should be replaced with Test1Name while MyTest should not be updated to MyTest1.
    I have tried to use below query which uses oracle regular expressions -
    SELECT REGEXP_REPLACE('MYCOMPANY TEST TESTGEET INDIA PVT LTD TEST','\s(TEST)\w',' TEST1') FROM DUAL
    Output -
    "MYCOMPANY TEST *TEST1EET* INDIA PVT LTD TEST"
    Here, it has also replaced the G also from TESTGEET and resulted in TEST1EET while i want TEST1GEET.
    Can someone please suggest how can i do this..... may b m doing some silly mistake but sorry m a newbie to regular expression...
    Thanks in advance..

  • How to replace a character in a string with blank space.

    Hi,
    How to replace a character in a string with blank space.
    Note:
    I have to change string  CL_DS_1===========CM01 to CL_DS_1               CM01.
    i.e) I have to replace '=' with ' '.
    I have already tried with <b>REPLACE ALL OCCURRENCES OF '=' IN temp_fill_string WITH ' '</b>
    Its not working.

    Hi,
    Try with this..
    call method textedit- >replace_all
      exporting
        case_sensitive_mode = case_sensitive_mode
        replace_string = replace_string
        search_string = search_string
        whole_word_mode = whole_word_mode
      changing
        counter = counter
      exceptions
        error_cntl_call_method = 1
        invalid_parameter = 2.
    <b>Parameters</b>      <b> Description</b>    <b> Possible values</b>
    case_sensitive_mode    Upper-/lowercase       false Do not observe (default value)
                                                                       true  Observe
    replace_string                Text to replace the 
                                         occurrences of
                                         SEARCH_STRING
    search_string                 Text to be replaced
    whole_word_mode          Only replace whole words   false Find whole words and                                                                               
    parts of words (default                                                                               
    value)
                                                                               true  Only find whole words
    counter                         Return value specifying how
                                        many times the search string
                                        was replaced
    Regards,
      Jayaram...

  • Replace a character in a String array

    I have an array of strings and am trying to replace the ' character with a space. I keep getting either a cannot be applied or cannot resolve symbol error. Can anyone help?
    String arrayList = request.getParameter("field");
    String newList = arrayList.replace("\'", " ");

    the replace method of the String class takes two parameters and both of them are characters not strings use it like this
    arrayList.replace('\'', ' ');that should fix it

  • Replacing the \ character in a string

    I'm having trouble replacing a backslash in a string. I use .indexOf() to find the character, but I have to use an escape character and write .index("\\"), but it doesn't work - it returns -1.
    Also, replace() doesn't work - gives me an java.util.regex.PatternSyntaxException. Any ideas?
    thx

    The escape is for the compiler, I think, and then you need to escape the backslash.
    Try "\\\\".
    � {�                                                                                                                                                                                                           

  • Replacing a character in a String

    Hi All,
    How can I replace a character ' which appears in a String into \'

    There is a method in String that replaces all
    occurrences of one character with anothercharacter.
    It's called, hold your breath now, "replace".But tho OP wants to replace one character with two
    characters :)You're right, I missed that. Well, serves me right for being sarcastic. :-)

  • Replace a character in the string using JavaScript

    Hello,
    I would like to ask for help. I have a field in the xml file, which contains a string, that is bound to a text box on the form.
    What would be the syntax to replace a special character in the string with the carriage return?
    Thank you.

    Huh?
    I didn't post my script...
    It sure is no clean programming since I just took Steve's solutions and delted the ligns I didn't want (the app allert)
    Though in the end I've taken the boolean out, or better replaced it with the replacement function, it repeats the replacement no matter how much "ü"'s are in there. (I needed the boolean though, since as long as it was true, the if should be executed.)
    Somehow it worked... not 100% sure why, but it worked.
    if (findChar(this.rawValue)) {
    function findChar(str)
    {  for (var i=0; i < str.length; i++)
            if (str.charAt(i) == "ü")
               this.rawValue = this.rawValue.replace(/ü/,"ue")

  • Replace a character from a string

    Hi,
    how can I replace a particular character from a string on a particular occurrence? Say for eg, if i wan to replace 'a' of second occurrence from 'abcabcabc', then what should i do? I guess the normal REPLACE function replaces every occurrence in a given string. So is there any other way to solve this?
    Thanks!

    If you are in 9i:
    Then you got to split the string into based on the nth position.
    SQL> select replace('abddefabc','a','x') from dual;
    REPLACE('
    xbddefxbc
    SQL> select instr('abddefabc','a',2) from dual;
    INSTR('ABDDEFABC','A',2)
                           7
    SQL> select substr('abddefabc',1,instr('abddefabc','a',2)-1),substr('abddefabc',instr('abddefabc','a',2)) from dual;
    SUBSTR SUB
    abddef abc
    SQL> select substr('abddefabc',1,instr('abddefabc','a',2)-1),replace(substr('abddefabc',instr('abddefabc','a',2)),'a','X') as replaced from dual;
    SUBSTR REP
    abddef XbcOfcourse, later on you can join the string..
    Jithendra

  • Replace hex character in a string with another hex character

    Hi Guys,
    Heres a problem scenario, hex character 92 looks very much like hex character 27 (apostrophe).
    I need to write a program that can replace all hex character 92 to hex 27 in a string.
    Being a novice on the regular expressions, I would appreciate if somebody can show
    the exact syntax to to perform this replacement.
    Many Thanks
    -Anil

    I don't think you need to use regex to do this:
    String s = something();
    char a = 0x27;
    char b = 0x92;
    s.replace(a,b);
    And don't forget that since Strings are immutable you need:
    s = s.replace(a,b);to do anything useful.

  • How to replace a character in a string

    Hello Powerusers
    First i'me new in the applescripting so hope you can tell me a few hint to get on.
    I Have been trying to find a way to replace characters in a string using applescript. but with no luck
    Anybody having a script that can give me a clue on this.
    I'me normally programming in windows.... yeah i know there is a first time for everything.

    Okay i solved my problem but why arent the folder renamed?
    property oldfolder : ""
    property newfolder : ""
    property SS : "."
    property RS : " "
    to replaceText(someText, oldItem, newItem)
         replace all occurances of oldItem with newItem
              parameters -     someText [text]: the text containing the item(s) to change
                        oldItem [text, list of text]: the item to be replaced
                        newItem [text]: the item to replace with
              returns [text]:     the text with the item(s) replaced
              set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, oldItem}
              try
                        set {itemList, AppleScript's text item delimiters} to {text items of someText, newItem}
                        set {someText, AppleScript's text item delimiters} to {itemList as text, tempTID}
              on error errorMessage number errorNumber -- oops
                        set AppleScript's text item delimiters to tempTID
                        error errorMessage number errorNumber -- pass it on
              end try
              return someText
    end replaceText
    tell application "Finder"
              set these_items to the selection
    end tell
    repeat with i from 1 to the count of these_items
              set this_item to (item i of these_items) as alias
              set this_info to info for this_item
              set oldfolder to name of this_info
              set newfolder to replaceText(oldfolder, SS, RS)
              set name of this_info to newfolder
    end repeat

  • Replacing a special character in a string with another string

    Hi
    I need to replace a special character in a string with another string.
    Say there is a string -  "abc's def's are alphabets"
    and i need to replace all the ' (apostrophe) with &apos& ..which should look like as below
    "abc&apos&s def&apos&s are alphabets" .
    Kindly let me know how this requirement can be met.
    Regards
    Sukumari

    REPLACE
    Syntax Forms
    Pattern-based replacement
    1. REPLACE [{FIRST OCCURRENCE}|{ALL OCCURRENCES} OF]
    pattern
              IN [section_of] dobj WITH new
              [IN {BYTE|CHARACTER} MODE]
              [{RESPECTING|IGNORING} CASE]
              [REPLACEMENT COUNT rcnt]
              { {[REPLACEMENT OFFSET roff]
                 [REPLACEMENT LENGTH rlen]}
              | [RESULTS result_tab|result_wa] }.
    Position-based replacement
    2. REPLACE SECTION [OFFSET off] [LENGTH len] OF dobj WITH new
                      [IN {BYTE|CHARACTER} MODE].
    Effect
    This statement replaces characters or bytes of the variable dobj by characters or bytes of the data object new. Here, position-based and pattern-based replacement are possible.
    When the replacement is executed, an interim result without a length limit is implicitly generated and the interim result is transferred to the data object dobj. If the length of the interim result is longer than the length of dobj, the data is cut off on the right in the case of data objects of fixed length. If the length of the interim result is shorter than the length of dobj, data objects of fixed length are filled to the right with blanks or hexadecimal zeroes. Data objects of variable length are adjusted. If data is cut off to the right when the interim result is assigned, sy-subrc is set to 2.
    In the case of character string processing, the closing spaces are taken into account for data objects dobj of fixed length; they are not taken into account in the case of new.
    System fields
    sy-subrc Meaning
    0 The specified section or subsequence was replaced by the content of new and the result is available in full in dobj.
    2 The specified section or subsequence was replaced in dobj by the contents of new and the result of the replacement was cut off to the right.
    4 The subsequence in sub_string was not found in dobj in the pattern-based search.
    8 The data objects sub_string and new contain double-byte characters that cannot be interpreted.
    Note
    These forms of the statement REPLACE replace the following obsolete form:
    REPLACE sub_string WITH
    Syntax
    REPLACE sub_string WITH new INTO dobj
            [IN {BYTE|CHARACTER} MODE]
            [LENGTH len].
    Extras:
    1. ... IN {BYTE|CHARACTER} MODE
    2. ... LENGTH len
    Effect
    This statement searches through a byte string or character string dobj for the subsequence specified in sub_string and replaces the first byte or character string in dobj that matches sub_string with the contents of the data object new.
    The memory areas of sub_string and new must not overlap, otherwise the result is undefined. If sub_string is an empty string, the point before the first character or byte of the search area is found and the content of new is inserted before the first character.
    During character string processing, the closing blank is considered for data objects dobj, sub_string and new of type c, d, n or t.
    System Fields
    sy-subrc Meaning
    0 The subsequence in sub_string was replaced in the target field dobj with the content of new.
    4 The subsequence in sub_string could not be replaced in the target field dobj with the contents of new.
    Note
    This variant of the statement REPLACE will be replaced, beginning with Release 6.10, with a new variant.
    Addition 1
    ... IN {BYTE|CHARACTER} MODE
    Effect
    The optional addition IN {BYTE|CHARACTER} MODE determines whether byte or character string processing will be executed. If the addition is not specified, character string processing is executed. Depending on the processing type, the data objects sub_string, new, and dobj must be byte or character type.
    Addition 2
    ... LENGTH len
    Effect
    If the addition LENGTH is not specified, all the data objects involved are evaluated in their entire length. If the addition LENGTH is specified, only the first len bytes or characters of sub_string are used for the search. For len, a data object of the type i is expected.
    If the length of the interim result is longer than the length of dobj, data objects of fixed length will be cut off to the right. If the length of the interim result is shorter than the length of dobj, data objects of fixed length are filled to the right with blanks or with hexadecimal 0. Data objects of variable length are adapted.
    Example
    After the replacements, text1 contains the complete content "I should know that you know", while text2 has the cut-off content "I should know that".
    DATA:   text1      TYPE string       VALUE 'I know you know',
            text2(18)  TYPE c LENGTH 18  VALUE 'I know you know',
            sub_string TYPE string       VALUE 'know',
            new        TYPE string       VALUE 'should know that'.
    REPLACE sub_string WITH new INTO text1.
    REPLACE sub_string WITH new INTO text2.

  • How to replace only the first specified character in a string and leave other occurrence of the character alone.

    Hello my Friends:
    I have a string that looks like this in a column:
    Hello, World, Hello, Planet
    I want to replace only the first occurrence so that the result looks like this:
    Hello World, Hello, Planet
    Working on some bad data source.
    I need to replace the character regardless of it's location as long as it is the first.
    I tried something like this, but I soon discovered that if the comma or character is missing the the string may get truncated or altered. If there are no characters in the string, then I want to simply leave it alone.
    Here is where I am at:
    DECLARE @MyValue NVARCHAR(MAX) = 'Hello, World, Hello, Planet';
    SELECT MyString = STUFF('Hello, World', CHARINDEX(',', @MyValue, 0), 1, ' ');
    Thanks my friends.

    I have a string that looks like this in a column:
    Hello, World, Hello, Planet
    Why doesn't it say Hello Kitty?
    Oh, sorry about that. Anyway:
    SELECT MyString = CASE WHEN CHARINDEX(',', @MyValue, 0) >= 1
                           THEN STUFF(MyString, CHARINDEX(',', @MyValue, 0), 1, ' ')
                           ELSE MyString
                     END;
    Erland Sommarskog, SQL Server MVP, [email protected]
    Erland, love you sense of humor!! :)
    Thanks for the solution.

  • Replace tab character from string in ABAP

    hi experts,
    I have a string like this "a<tab character>b<tab character>c<tab character>d". for my processing i want the output like "abcd". How can i replace all occurances of this tab character from my string.
    tab character = a hexa decimal character. I dont know the hex value for this.
    regards
    Raghav

    hi you joined SCN in 2007 its a way long time to say.. ur new.. any ways.
    after declaring the lv_tab as I said...
    REPLACE ALL OCCURRENCES OF lv_tab in <string> with space.

  • How to count number of occurences of a character  in a string

    I want to get the count of occurences of a character within a string. Is there any function for this or should i go for a PLSQL.
    For example is the sting is "occurences" & if i search for character "c", the answer should be 3.
    Regards,
    Sunil.

    SQL> select length('occurence') - length(replace('occurence','c')) from dual;
    LENGTH('OCCURENCE')-LENGTH(REPLACE('OCCURENCE','C'))
    3

  • Function in oracle to find number of occurances of a character in a string

    hi,
    is there any function in oracle to find the number of ocurrances of a character in a string ?
    or is there any simple way of doing the same, rather than writting many lines of code as my program is already very complex.
    Maria

    Hi Maria,
    I don't know of such a function in Oracle, but maybe you could use this:
    length(search_string) - length(replace(search_string, character_to_be_found))
    For example: select length('Hello') - length ( replace('Hello', 'l')) from dual;
    Hope this is what you're looking for
    Danny

Maybe you are looking for

  • Good Receipt Indicator in PO

    Hello; I wanted to know if someone experienced something about the good receipt indicator (GRI) in the PO, when the PO line item has an account assignment the good receipt indicator in the delivery tab becomes active but if the PO line item does not

  • Dimension declaration. Why do we need it?

    Hey, Oracle data warehouse gurus. It should be an easy question for you. Why do we need to declare dimension on the top of the dimension table (CREATE DIMENTION dimension_name ...)? It seems to me that many functions such as rollup, cube and the like

  • NB 305 7 Starter Restore "Preparing Computer for first" use how long stuck??

    OK, I've searched far and wide for a straight forward answer on this, but I can't seem to find one anywhere...  So I did a restore on my NB because the guy I bought it from had deleted everything, but didn't do a restore, and It's running 7 starter,

  • Resource path

    First I checked it was all OK without POSIX and it works: display dialog "Open last saved or choose file" buttons {"Open last", "Open other"} default button 2 if button returned of result is "Open last" then set val1 to alias (read file "Macintosh HD

  • APO DP - descriptive characteristics used in consumption groups

    I am using APO DP V5. I need to use descriptive characteristics in consumption groups ( for use in release of DP to SNP). Do these descriptive characteristics have to be planning characteristics of the planning object structure, or can they also be n