【问题标题】:Finding fields in String java regular expression在String java正则表达式中查找字段
【发布时间】:2013-06-24 13:02:34
【问题描述】:

我不擅长 Java 正则表达式。

我有以下文字

[[image:testimage.png||height=\"481\" width=\"816\"]]

我想从上面的文本中提取图像:、高度和宽度。有人可以帮我写正则表达式来实现吗?

【问题讨论】:

  • 试错的好工具:Regexp Editor
  • 另一个好工具是RegexPlanet
  • 你在问题​​的末尾缺少一些东西......“我有 n”??

标签: java regex pattern-matching expression


【解决方案1】:

试试这个正则表达式:

((?:image|height|width)\D+?([a-zA-Z\d\.\\"]+))

你会得到两组。

例如,

  1. 身高=\"481\"
  2. 481

【讨论】:

    【解决方案2】:

    如果这是您的确切字符串

    [[image:testimage.png||height=\"481\" width=\"816\"]]
    

    然后尝试以下(原油):

    String input = // read your input string
    String regex = ".*height=\\\\\"(\\d+)\\\\\" width=\\\\\"(\\d+)"
    String result = input.replaceAll(regex, "$1 $2");
    String[] height_width = result.split(" ")
    

    这是一种方法,另一种(更好的)方法是使用Pattern

    【讨论】:

      【解决方案3】:

      此正则表达式将匹配一个属性及其关联值。您必须遍历它在源字符串中找到的每个匹配项,以获取所需的所有信息。

      (\w+)[:=]("?)([\w.]+)\2
      

      您有三个捕获组。您对其中两个感兴趣:

      • 组 1:属性的名称。 (图像、高度、宽度...)
      • 第 3 组:属性的值。

      下面是正则表达式的细分:

      (\w+)       #Group 1: Match the property name.
      [:=]        #The property name/value separator.
      ("?)        #Group 2: The string delimiter.
      ([\w.]+)    #Group 3: The property value. (Accepts letters, numbers, underscores and periods)
      \2          #The closing string delimiter if there was one.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-12
        • 1970-01-01
        • 1970-01-01
        • 2011-04-13
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        相关资源
        最近更新 更多