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

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

问题描述

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



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

 (http | https):\ / \ /(\w +:{0,1} \ ?!?W * @)(\S +)(:[0-9] +)(\ / | \ /([\w#:+ =放大器;%@  -  \! /]))? 

不幸的是,Java编译器当然无法解析该字符串,因为它没有使用有效的转义序列(因为上面技术上是JavaScript的一种url模式,而不是Java)



在这一天结束时,我正在寻找一种正则表达式模式, Java和正确执行JavaScript。

解决方案

您将不得不使用JSNI在Javascript中执行正则表达式评估部分。如果你用正确的反斜杠编写正则表达式,那么它会被转换成Javascript,因为它显然是无效的。认为它可以在Hosted或Dev模式下工作,因为它仍然运行Java字节码,但不在编译的应用程序中。



一个简单的JSNI示例来测试给定的字符串是一个有效的URL:

  // Java方法
public native boolean isValidUrl(String url)/ * - {
var pattern = /(http | https):\ / \ /(\w +:{0,1} \w * @)?(\S +)(:[0-9] +)? ?(\ / | \ /([!?!\w#:+ =安培;%@-\ /]))/;
返回pattern.test(url);
} - * /;

Java和Javascript正则表达式引擎之间可能存在其他不规则性,因此最好将其完全卸载到Javascript至少适用于中等复杂的正则表达式。

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#!:.?+=&%@!\-\/]))?

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)

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

解决方案

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.

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);
}-*/;

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天全站免登陆