正则匹配年份
Regex matching year
我正在尝试使用此正则表达式匹配从 19 或 20 开始的年份
/(19|20)\d{2}/
name = "My example 2004-2005"
years = Regex.scan(~r/(19|20)\d{2}/, name)
IO.inspect(years)
我期待
["2004", "2005"]
但是我得到了
[["2004", "20"], ["2005", "20"]]
我不知道为什么 "20"
也被退回了。我也试过了
/(19|20){1}\d{2}/
这是因为当您将 19|20
括在一对括号中时,您创建了一个捕获组。这代表一个子匹配。要创建一个组但不将其计为单独的子捕获,请使用非捕获组。它有这样的语法:(?:)
因此在您的示例中,它将是:
/(?:19|20)\d{2}/
但是,结果仍然是列表的列表:
[["2004"], ["2005"]]
使用List.flatten()
将列表展平为一维列表:
IO.inspect(List.flatten(years))
要return只抓全,可以用capture modifier capture: :first
passed as the third parameter to Regex.scan/3
。
它仍然会 return 列表的列表,因此您需要使用 List.flatten/1
或使用理解
来展平结果
for [c] <- Regex.scan(~r/(19|20)\d{2}/, name, capture: :first), do: c
#⇒ ["2004", "2005"]
我认为在这种情况下,如果您首先使用 String.split/3
, then use Enum.filter/2
提取年份,然后使用正则表达式过滤有效年份,会更清楚:
"My example 2004-2005-1816-1905-401"
|> String.split(["My example ", "-"], trim: true)
|> Enum.filter(&(&1 =~ ~r/(19|20)\d{2}/))
结果:
["2004", "2005", "1905"]
我正在尝试使用此正则表达式匹配从 19 或 20 开始的年份
/(19|20)\d{2}/
name = "My example 2004-2005"
years = Regex.scan(~r/(19|20)\d{2}/, name)
IO.inspect(years)
我期待
["2004", "2005"]
但是我得到了
[["2004", "20"], ["2005", "20"]]
我不知道为什么 "20"
也被退回了。我也试过了
/(19|20){1}\d{2}/
这是因为当您将 19|20
括在一对括号中时,您创建了一个捕获组。这代表一个子匹配。要创建一个组但不将其计为单独的子捕获,请使用非捕获组。它有这样的语法:(?:)
因此在您的示例中,它将是:
/(?:19|20)\d{2}/
但是,结果仍然是列表的列表:
[["2004"], ["2005"]]
使用List.flatten()
将列表展平为一维列表:
IO.inspect(List.flatten(years))
要return只抓全,可以用capture modifier capture: :first
passed as the third parameter to Regex.scan/3
。
它仍然会 return 列表的列表,因此您需要使用 List.flatten/1
或使用理解
for [c] <- Regex.scan(~r/(19|20)\d{2}/, name, capture: :first), do: c
#⇒ ["2004", "2005"]
我认为在这种情况下,如果您首先使用 String.split/3
, then use Enum.filter/2
提取年份,然后使用正则表达式过滤有效年份,会更清楚:
"My example 2004-2005-1816-1905-401"
|> String.split(["My example ", "-"], trim: true)
|> Enum.filter(&(&1 =~ ~r/(19|20)\d{2}/))
结果:
["2004", "2005", "1905"]