【问题标题】:How to convert an IP address range to Regex?如何将 IP 地址范围转换为正则表达式?
【发布时间】:2020-10-14 04:28:27
【问题描述】:

我想配置 tomcat internalProxies 远程 IP 阀来信任 Google GFE source addresses 这是

  • 35.191.0.0/16
  • 130.211.0.0/22

Tomcat 只接受这些值的正则表达式。

  • 将 IP 地址范围转换为 java.util.Regex 的公式是什么?
  • 是否有任何工具可以将 IP 地址范围转换为正则表达式?

【问题讨论】:

标签: java regex ip


【解决方案1】:

我找到了这个工具here。如果您在提供的正则表达式中删除\ 之前的反斜杠\ 似乎与java.util.regex.Pattern 兼容。

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class IPMatchTester {

     public static void main(String []args){
         // For 35.191.0.0/16
         Pattern p = Pattern.compile("^(35.191.(?:[0-9]|[1-9][0-9]|1(?:[0-9][0-9])|2(?:[0-4][0-9]|5[0-5])).(?:[0-9]|[1-9][0-9]|1(?:[0-9][0-9])|2(?:[0-4][0-9]|5[0-5])))$");
         int matchCount = 0;
         for( int j = 0; j <= 255; j++){
             for( int i = 0; i <= 255; i++){
                 if(!p.matcher("35.191."+ j +"." +i ).matches()){
                     System.out.println("35.191." + j + "."+ i + " no matched ");
                 } else{
                     matchCount++;
                 }
             }
         }
         System.out.println("Number of ip matched: " + matchCount);
         
         
         // For 130.211.0.0/22
         Pattern p2 = Pattern.compile("^(130.211.(?:[0-3]).(?:[0-9]|[1-9][0-9]|1(?:[0-9][0-9])|2(?:[0-4][0-9]|5[0-5])))$");
         int matchCount2 = 0;
         for( int j = 0; j <= 3; j++){
             for( int i = 0; i <=255; i++){
                 if(!p2.matcher("130.211."+ j +"." +i ).matches()){
                     System.out.println("130.211." + j + "."+ i + " no matched ");
                 } else{
                     matchCount2++;
                 }
             }
         }
         System.out.println("Number of ip matched: " + matchCount2);
     }
}

【讨论】:

    猜你喜欢
    • 2012-12-23
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    相关资源
    最近更新 更多