gpt4 book ai didi

regex - 在 Erlang 中将 IP 地址与正则表达式匹配

转载 作者:行者123 更新时间:2023-12-04 23:08:32 24 4
gpt4 key购买 nike

我正在研究 re Erlang 的模块,我只想匹配 URL 中的 IP 地址:

Url = "http://192.168.1.241/mod/fun?arg",
re:run(Url, "(\\d{1,3}\\.){3}\\d{1,3}", [{capture, all, list}]).

但它返回 {match,["192.168.1.168","1."]}对我来说。为什么是 "1."在退货 list 中?

最佳答案

您已为 ValueSpec 指定“全部”,这意味着您将获得所有匹配的子组。在这种情况下,包括“1.”。而不是“全部”,您可以只指定“第一个”,您将得到的只是第一个匹配组(完整的 IP)。
你应该这样做:

Url = "http://192.168.1.241/mod/fun?arg",
re:run(Url, "(\\d{1,3}\\.){3}\\d{1,3}", [{capture, first, list}]).
这将返回:
{match,["192.168.1.241"]}
更多信息 here .
编辑:以防万一您错过了,这是文档中的相关部分(比我解释得更好:-)):

Specifies which captured (sub)patterns are to be returned. The ValueSpec can either be an atom describing a predefined set of return values, or a list containing either the indexes or the names of specific subpatterns to return.

The predefined sets of subpatterns are:

all

All captured subpatterns including the complete matching string. This is the default.

first

Only the first captured subpattern, which is always the complete matching part of the subject. All explicitly captured subpatterns are discarded.

all_but_first

All but the first matching subpattern, i.e. all explicitly captured subpatterns, but not the complete matching part of the subject string. This is useful if the regular expression as a whole matches a large part of the subject, but the part you're interested in is in an explicitly captured subpattern. If the return type is list or binary, not returning subpatterns you're not interested in is a good way to optimize.

none

Do not return matching subpatterns at all, yielding the single atom match as the return value of the function when matching successfully instead of the {match, list()} return. Specifying an empty list gives the same behavior.

关于regex - 在 Erlang 中将 IP 地址与正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5801080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com