diff --git a/NEWS.md b/NEWS.md index 7b6beb3a10a6d..c314275602e40 100644 --- a/NEWS.md +++ b/NEWS.md @@ -44,6 +44,7 @@ Standard library changes * `startswith` and `endswith` now accept a `Regex` for the second argument ([#29790]). * `retry` supports arbitrary callable objects ([#30382]). * A no-argument construct to `Ptr{T}` has been added which constructs a null pointer ([#30919]) +* `strip` now accepts a function argument in the same manner as `lstrip` and `rstrip` ([#31211]) #### LinearAlgebra diff --git a/base/strings/util.jl b/base/strings/util.jl index 697c19a34a2dd..d065cb15c69f5 100644 --- a/base/strings/util.jl +++ b/base/strings/util.jl @@ -195,9 +195,11 @@ rstrip(s::AbstractString) = rstrip(isspace, s) rstrip(s::AbstractString, chars::Chars) = rstrip(in(chars), s) """ - strip(str::AbstractString, [chars]) + strip([pred=isspace,] str::AbstractString) + strip(str::AbstractString, chars) -Remove leading and trailing characters from `str`. +Remove leading and trailing characters from `str`, either those specified by `chars` or +those for which the function `pred` returns `true`. The default behaviour is to remove leading whitespace and delimiters: see [`isspace`](@ref) for precise details. @@ -205,6 +207,9 @@ The default behaviour is to remove leading whitespace and delimiters: see The optional `chars` argument specifies which characters to remove: it can be a single character, vector or set of characters. +!!! compat "Julia 1.2" + The method which accepts a predicate function requires Julia 1.2 or later. + # Examples ```jldoctest julia> strip("{3, 5}\\n", ['{', '}', '\\n']) @@ -212,7 +217,8 @@ julia> strip("{3, 5}\\n", ['{', '}', '\\n']) ``` """ strip(s::AbstractString) = lstrip(rstrip(s)) -strip(s::AbstractString, chars) = lstrip(rstrip(s, chars), chars) +strip(s::AbstractString, chars::Chars) = lstrip(rstrip(s, chars), chars) +strip(f, s::AbstractString) = lstrip(f, rstrip(f, s)) ## string padding functions ## diff --git a/test/strings/util.jl b/test/strings/util.jl index 17d1f9355006c..b675bdf6531b8 100644 --- a/test/strings/util.jl +++ b/test/strings/util.jl @@ -53,6 +53,7 @@ end @test strip(" \u2009 hi \u2009 ") == "hi" @test strip("foobarfoo", ['f','o']) == "bar" @test strip("foobarfoo", ('f','o')) == "bar" + @test strip(ispunct, "¡Hola!") == "Hola" for s in ("", " ", " abc", "abc ", " abc "), f in (lstrip, rstrip, strip)