【问题标题】:Pass a Regular Expression via URL通过 URL 传递正则表达式
【发布时间】:2021-02-02 02:21:50
【问题描述】:

我有这样的资源端点:'.../rest/regex/{regex:.+}/matches{value:.+}'; 我怎样才能安全地通过 url 中的正则表达式?如何编码?

在javascript中我尝试过:

        public matches(regex: string, value: string): ng.IPromise<boolean> {
            return this.RestService.httpGet(this.path +  this.escapeRegExp(regex) +
                '/matches/' + encodeURIComponent(value));
        }

        escapeRegExp(str: string) {
            return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
        }

但是当我使用这个正则表达式:TNGSXGIN02BZ0(1|3)[1][8-9][0-5][0-9]\d{4} 然后服务器端(java)我得到这个错误: java.util.regex.PatternSyntaxException: Unclosed counted closure near index 60 (?i)^TNGSXGIN02BZ0/(1/|3/)/[1/]/[8/-9/]/[0/-5/]/[0/-9/]/d/{4/}$

Java 代码如下所示:

@Path("regex")
@RunInTransaction
@Produces(MediaType.TEXT_PLAIN)
public final class RegexService {
    private static final Logger LOG = Log.getLogger();

    @GET
    @Path("{regex:.+}/matches/{value:.+}")
    public boolean matches(@PathParam("regex") String regex, @PathParam("value") String value) {
        LOG.debug("GET Test regex: {} with value: {}", regex, value);
        return Pattern.matches("(?i)^" + regex + "$", value);
    }
}

更新: 当我在 javascript 中有这个时:

        public matches(regex: string, value: string): ng.IPromise<boolean> {
            return this.RestService.httpGet(this.path +  encodeURIComponent(regex) +
                '/matches/' + encodeURIComponent(value));
        }

这在 Java 中:

    @GET
    @Path("{regex:.+}/matches/{value:.+}")
    public boolean matches(@PathParam("regex") String regex, @PathParam("value") String value) {
        LOG.debug("GET Test regex: {} with value: {}", URLDecoder.decode(regex, StandardCharsets.UTF_8), value);
        return Pattern.matches("(?i)^" + URLDecoder.decode(regex, StandardCharsets.UTF_8) + "$", value);
    }

我仍然遇到异常:

java.util.regex.PatternSyntaxException:索引 60 附近的未闭合计数闭合 (?i)^TNGSXGIN02BZ0/(1/|3/)/[1/]/[8/-9/]/[0/-5/]/[0/-9/]/d/{4/} $

【问题讨论】:

    标签: javascript java regex


    【解决方案1】:

    【讨论】:

    【解决方案2】:

    你也可以使用 String 构造函数:

    let regex = new RegExp(".*", "g");
    let urlRegex = encodeURIComponent(String(regex));
    console.log(urlRegex);
    
    let regexresult = new RegExp(decodeURIComponent(urlRegex));
    console.log(decodeURIComponent(urlRegex));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多