2017-09-15 22 views
1

給定一個輸入字符串,我想只使用正則表達式來查找字符串中以特定順序存在的特定字符的次數。我一直使用正則表達式來匹配表達式,但從不計數字符。不太確定如何去做。所以我只使用模式匹配尋找解決這個問題的方法。如何統計字符串中某些特定的前導字符的數量,僅使用Regex?

例如說我的例子字符串S =「0004fhjs0sjk0」 ,我需要計算的領先數「0」字符串s,這是3在這種情況下。如何定義它返回計數(3這裏)

def get_leading_zeroes(value, character) do 
... 
end 

我已經實現了使用遞歸解決方案的功能,但我想用正則表達式來做到這一點。

def get_leading_zeros(value, count) do 
[h|t] = value 
if h == "0" do 
    get_leading_zeros(t, count+1) 
else 
    count 
end 

get_leading_zeros(value |> String.graphemes, 0) 
+0

'字符'只有一個碼點或者它可以是一個長字符串?另外,你是否嘗試自己實現這一點? (如果是的話,你應該添加非工作代碼)。 – Dogbert

+0

對不起,我更新了這個問題。我使用遞歸解決了它,但想知道Elixir中是否有其他更好的方法來實現它,主要是通過使用模式匹配而不是檢查單個字符。 – Shubh77

回答

1

隨着遞歸(更好圖案匹配+尾優化):

defmodule M do 
    def get_leading_zeros(input, acc \\ 0) # declaration for default 
    def get_leading_zeros(<<"0", rest :: binary>>, acc), 
    do: get_leading_zeros(rest, acc + 1) # recursive call when matches 
    def get_leading_zeros(_, acc), do: acC# return accumulated 
end 
M.get_leading_zeros "0004fhjs0sjk0" 
#⇒ 3 

隨着正則表達式:

with [match] <- Regex.run(~r/\A0*/, "0004fhjs0sjk0"), 
    do: String.length(match) 

如果沒有額外的調用:

with [{pos, _}] <- 
    Regex.run(~r/[^0]/, # negative search 
       "0004fhjs0sjk0", 
       return: :index, capture: :first), # NOTE return: :index 
    do: pos 

,或者反之亦然:

with [{0, pos}] <- 
    Regex.run(~r/0*/, # positive search 
       "0004fhjs0sjk0", 
       return: :index, capture: :first), 
    do: pos 

也請檢查下面通過一個@Dogbert有價值的評論,但是這是一個習慣問題。

+2

我會用'「0」<> rest'而不是'<<「0」,rest :: binary >>'。 – Dogbert

0
def get_leading_char_count(str, char) do 
    ~r/^#{char}*/ 
    |> Regex.run(str) 
    |> Enum.at(0) 
    |> String.length() 
end 

get_leading_char_count("0004fhjs0sjk0", 0) 
# 3 

get_leading_char_count("4fhjs0sjk0", 0) 
# 0 

注:我在我的例子改名功能,因爲你是在零傳遞在你自己的例子第二個參數。如果你傳遞的不是零,函數名稱get_leading_zeroes將不再有意義。

相關問題