GWT 中的正则表达式匹配 URL [英] Regex in GWT to match URLs

查看:27
本文介绍了GWT 中的正则表达式匹配 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了 Pattern 类,如下所示:http://www.java2s.com/Code/Java/GWT/ImplementjavautilregexPatternwithJavascriptRegExpobject.htm

I implemented the Pattern class as shown here: http://www.java2s.com/Code/Java/GWT/ImplementjavautilregexPatternwithJavascriptRegExpobject.htm

我想使用以下正则表达式来匹配我的字符串中的网址:

And I would like to use the following regex to match urls in my String:

(http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?

不幸的是,Java 编译器在解析该字符串时当然会失败,因为它没有使用有效的转义序列(因为从技术上讲,上面是 JavaScript 的 url 模式,而不是 Java)

Unfortunately, the Java compiler of course fails on parsing that string because it doesn't use valid escape sequences (since the above is technically a url pattern for JavaScript, not Java)

归根结底,我正在寻找一种既能在 Java 中编译又能在 JavaScript 中正确执行的正则表达式模式.

At the end of the day, I'm looking for a regex pattern that will both compile in Java and execute in JavaScript correctly.

推荐答案

您将不得不使用 JSNI 在 Javascript 中执行正则表达式评估部分.如果您确实使用转义的反斜杠编写了正则表达式,那么它将按原样转换为 Javascript,并且显然是无效的.认为它可以在托管或开发模式下运行,因为它仍在运行 Java 字节码,但不适用于已编译的应用程序.

You will have to use JSNI to do the regex evaluation part in Javascript. If you do write the regex with the escaped backslashes, that will get converted to Javascript as it is and will obviously be invalid. Thought it will work in the Hosted or Dev mode as thats still running Java bytecode, but not on the compiled application.

测试给定字符串是否为有效 URL 的简单 JSNI 示例:

A simple JSNI example to test if a given string is a valid URL:

// Java method
public native boolean isValidUrl(String url) /*-{
    var pattern = /(http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?/;
    return pattern.test(url);
}-*/;

Java 和 Javascript 正则表达式引擎之间可能存在其他违规行为,因此最好将其完全卸载到 Javascript,至少对于中等复杂的正则表达式.

There may be other irregularities between the Java and Javascript regex engines, so it's better to offload it completely to Javascript at least for moderately complex regexes.

这篇关于GWT 中的正则表达式匹配 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆