Elixir Sigils #
一、Sigils概述 #
1.1 什么是Sigils #
Sigils是Elixir的特殊语法糖,以 ~ 开头,用于处理特定格式的文本。
1.2 基本语法 #
elixir
~s(Hello, World!)
~r/hello/
~w(one two three)
二、内置Sigils #
2.1 ~s - 字符串 #
elixir
iex(1)> ~s(Hello, World!)
"Hello, World!"
iex(2)> ~s(Hello #{name})
"Hello Alice"
iex(3)> ~S(Hello #{name})
"Hello \#{name}"
小写 ~s 支持插值和转义,大写 ~S 不支持。
2.2 ~c - 字符列表 #
elixir
iex(1)> ~c(hello)
'hello'
iex(2)> ~c(hello #{name})
'hello Alice'
iex(3)> ~C(hello #{name})
'hello \#{name}'
2.3 ~r - 正则表达式 #
elixir
iex(1)> ~r/hello/
~r/hello/
iex(2)> Regex.match?(~r/hello/, "hello world")
true
iex(3)> Regex.replace(~r/hello/, "hello world", "hi")
"hi world"
iex(4)> ~r/hello/i
~r/hello/i
正则修饰符:
i- 忽略大小写m- 多行模式s- 单行模式x- 扩展模式
2.4 ~w - 单词列表 #
elixir
iex(1)> ~w(hello world)
["hello", "world"]
iex(2)> ~w(hello world)a
[:hello, :world]
iex(3)> ~w(hello world)c
['hello', 'world']
iex(4)> ~w(hello world)s
["hello", "world"]
修饰符:
a- 原子c- 字符列表s- 字符串(默认)
2.5 ~D - 日期 #
elixir
iex(1)> ~D[2024-01-15]
~D[2024-01-15]
2.6 ~T - 时间 #
elixir
iex(1)> ~T[12:00:00]
~T[12:00:00]
iex(2)> ~T[12:00:00.123456]
~T[12:00:00.123456]
2.7 ~N - 日期时间 #
elixir
iex(1)> ~N[2024-01-15 12:00:00]
~N[2024-01-15 12:00:00]
2.8 ~U - UTC日期时间 #
elixir
iex(1)> ~U[2024-01-15 12:00:00Z]
~U[2024-01-15 12:00:00Z]
三、分隔符 #
3.1 可用分隔符 #
elixir
~s/hello/
~s|hello|
~s"hello"
~s'hello'
~s(hello)
~s[hello]
~s{hello}
~s<hello>
3.2 选择分隔符 #
根据内容选择合适的分隔符:
elixir
~s/path/to/file/
~s(string with (parentheses))
~s[string with [brackets]]
~s{string with {braces}}
四、自定义Sigils #
4.1 定义Sigil #
elixir
defmodule MySigils do
def sigil_u(content, _opts) do
String.upcase(content)
end
end
4.2 使用自定义Sigil #
elixir
iex(1)> import MySigils
iex(2)> ~u(hello world)
"HELLO WORLD"
4.3 带选项的Sigil #
elixir
defmodule MySigils do
def sigil_u(content, opts) do
cond do
?l in opts -> String.downcase(content)
?u in opts -> String.upcase(content)
?t in opts -> String.titlecase(content)
true -> content
end
end
end
使用:
elixir
~u(hello world)u
~u(HELLO WORLD)l
~u(hello world)t
4.4 大写Sigil #
大写Sigil不处理转义和插值:
elixir
defmodule MySigils do
def sigil_U(content, _opts) do
# content 是原始字符串
content
end
end
五、实用示例 #
5.1 Base64 Sigil #
elixir
defmodule Base64Sigil do
def sigil_b(content, _opts) do
Base.encode64(content)
end
def sigil_B(content, _opts) do
Base.decode64!(content)
end
end
5.2 JSON Sigil #
elixir
defmodule JsonSigil do
def sigil_j(content, _opts) do
Jason.decode!(content)
end
end
使用:
elixir
~j({"name": "Alice", "age": 30})
5.3 路径Sigil #
elixir
defmodule PathSigil do
def sigil_p(content, _opts) do
Path.expand(content)
end
end
六、总结 #
本章学习了:
| Sigil | 用途 |
|---|---|
~s |
字符串 |
~S |
原始字符串 |
~c |
字符列表 |
~r |
正则表达式 |
~w |
单词列表 |
~D |
日期 |
~T |
时间 |
~N |
日期时间 |
~U |
UTC日期时间 |
准备好学习元编程了吗?让我们进入下一章。
最后更新:2026-03-27