replace

replace(string, pat, r[, n])

Search for the given pattern pat, and replace each occurrence with r. If n is provided, replace at most n occurrences. As with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring. If pat is a regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding matched text.

Examples

  1. Replace a single occurrence in a string:

    julia> replace("Hello, world!", "world", "Julia")
    "Hello, Julia!"

    This example replaces the first occurrence of the string "world" with "Julia" in the given string.

  2. Replace multiple occurrences in a string:

    julia> replace("Julia is awesome. Julia is fast.", "Julia", "Python")
    "Python is awesome. Python is fast."

    It replaces all occurrences of the string "Julia" with "Python" in the given string.

  3. Replace using a regular expression pattern:

    julia> replace("Hello, 123!", r"\d+", "world")
    "Hello, world!"

    In this example, it uses a regular expression pattern \d+ to match one or more digits and replaces it with the string "world".

  4. Replace using a function:

    julia> replace("Hello, Julia!", "Julia") do s
              uppercase(s)
          end
    "Hello, JULIA!"

    It replaces the matched substring "Julia" with the uppercase version of itself using a provided function.

  5. Replace a limited number of occurrences:
    julia> replace("Hello, hello, hello, hello!", "hello", "hi", 2)
    "Hello, hi, hi, hello!"

    It replaces a maximum of 2 occurrences of the string "hello" with "hi" in the given string.

Common mistake example:

julia> replace("Hello, world!", 'o', "i")
ERROR: MethodError: no method matching replace(::String, ::Char, ::String)

In this example, the second argument is provided as a character ('o') instead of a string or regular expression. When using the replace function, ensure that the second argument is of the correct type (string or regular expression) to avoid such errors.

See Also

ascii, base64decode, Base64DecodePipe, base64encode, Base64EncodePipe, bin, bits, bytestring, charwidth, chomp, chop, chr2ind, contains, endswith, escape_string, graphemes, ind2chr, iscntrl, istext, isupper, isvalid, join, lcfirst, lowercase, lpad, lstrip, normalize_string, num2hex, parseip, randstring, readuntil, replace, repr, rpad, rsplit, rstrip, search, searchindex, split, startswith, string, stringmime, strip, strwidth, summary, takebuf_string, ucfirst, unescape_string, uppercase, utf16, utf32, utf8, wstring,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: