【问题标题】:Regular expression with URL Encoded Strings带有 URL 编码字符串的正则表达式
【发布时间】:2015-04-21 01:13:40
【问题描述】:

我的字符串包含 URL 编码 (%22) 和其他字符 [!@#$%^&*]。我需要使用正则表达式来检查字符串是否包含该组中的字符,但不包括 URL 编码的引号 (%22)。我无法让负面展望正常工作,也无法让排除的字符串(或否定)工作。有人可以帮忙吗?这是到目前为止不起作用的代码:

Pattern p = Pattern.compile("[!@#$%^&*]"); //
String[] tokens = {"%22Hobo%22", "Shoe*", "Rail%6Road","Sugar"};
for (String string : tokens) {
  Matcher m = p.matcher(string);
  boolean b = m.find()
  System.out.println(string + ": " + b);
}

所需的输出应该是假、真、真、假。

【问题讨论】:

  • 为什么不使用 URLEncoder?
  • 我在示例中添加的内容是为了方便和可读性。

标签: java regex pattern-matching


【解决方案1】:
export const uriParser = (x) =>
  //replace/regex exclude-negated [set-of-tokens], doesn't work/parse for (%[A-Fa-f0-9]{2})+
  //decodeURI() does the same I believe, but this will always return a string,
  //without an error object
  //a-z or A-Z includes underscore '_' but not space whitespace, nor (\r\n|\r|\n)+
  x.replace(/(%[A-Fa-f0-9]{2})+[^a-zA-Z0-9-+ ]+/g, "_");

https://www.ietf.org/rfc/rfc3986.txt#:~:text=2.4.%20%20When%20to%20Encode%20or%20Decode%0A

出于我的目的,我让我的 uri 链接片段在挂载时通过 (%[A-Fa-f0-9]{2})+,因此我将 .replace("_"," ") 用于 ui,但 uriParser() 用于 ux 中的传出链接,以尽可能绕过冗余。用例选择是在始终获取字符串和在此之前放置其他字符的规范之间。 “为什么不使用 URLEncoder?” – Jens 对问题的评论

【讨论】:

    【解决方案2】:
    (?!%22)[!@#$%^&*]
    

    试试这个。查看演示。

    https://regex101.com/r/mS3tQ7/16

    【讨论】:

    • 谢谢 vks,就是这样。我是如此接近,但有太多的表情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2013-10-21
    • 2017-02-15
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多