Erlang regex shared IP address

I am studying the re Erlang module and I just want to map the IP address in the url:

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

But he returned me {match,["192.168.1.168","1."]} . Why is "1." in the return list?

+4
source share
2 answers

You specified "all" for ValueSpec, which means that you will get all the relevant subgroups. In this case, it is "1.". Instead of “everything,” you can simply specify “first,” and all you get is the first corresponding group (full IP address).

You should do it as follows:

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

This will return:

 {match,["192.168.1.241"]} 

More details here .

EDIT: Just in case, if you miss it, here is the relevant part in the documents (which explain it much better than me :-)):

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

Predefined Subpattern Sets:

everything

All captured subpatterns, including the full matching string. This is the default value.

first

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

all_but_first

Everything except the first matching subpattern, i.e. all explicitly captured subpatterns, but not the full matching part of the subject line. This is useful if the regular expression as a whole matches a significant part of the object, but the part you are interested in is in a clearly captured subpattern. If the return type is a list or binary, then not returning subpatterns that you are not interested in is a good way to optimize.

no one

Do not return the corresponding subpatterns at all, giving a single atom match as the return value of the function on a successful match, rather than returning {match, list ()}. Specifying an empty list gives the same behavior.

+5
source

Try:

 ((?:\\d{1,3}\\.){3}\\d{1,3}) 

The current bracket matches only one part of the IP address. If you decide to ignore it and match the entire regular expression, you will get the correct result.

+4
source

All Articles