Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

Need a scala functional code for validating ipv4 and ipv6

I was trying to construct functional program for parsing IP address. I am seeing an error. I wanted a simpler code which differentiates ipv4 to ipv6. Here is the JAVA code.

import java.util.regex.Pattern;
class Solution {
  String chunkIPv4 = "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
  Pattern pattenIPv4 =
          Pattern.compile("^(" + chunkIPv4 + "\.){3}" + chunkIPv4 + "$");

  String chunkIPv6 = "([0-9a-fA-F]{1,4})";
  Pattern pattenIPv6 =
          Pattern.compile("^(" + chunkIPv6 + "\:){7}" + chunkIPv6 + "$");

  public String validIPAddress(String IP) {
    if (pattenIPv4.matcher(IP).matches()) return "IPv4";
    return (pattenIPv6.matcher(IP).matches()) ? "IPv6" : "Neither";
  }
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming your scala solution that you wrote in the comment has the following:

  def validIPAddress(IP: String): String = {
    if (pattenIPv4.matcher(IP).matches()) "IPv4"
    if (pattenIPv6.matcher(IP).matches()) "IPv6"
    else "Neither"
  }

The first if line will be evaluated but will not return without a return keyword, so it will fall through the next conditional. You can fix that in two ways, one is to add return:

if (pattenIPv4.matcher(IP).matches()) return "IPv4"

or maybe better add an else to the second line, so you can avoid the return as the whole thing will be evaluated as a single expression:

  def validIPAddress(IP: String): String = {
    if (pattenIPv4.matcher(IP).matches()) "IPv4"
    else if (pattenIPv6.matcher(IP).matches()) "IPv6"
    else "Neither"
  }

Also, as a side note, all those vars can be vals since you are not mutating them, and it's a good practice in scala to have the guarantee that they will always have the same value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...