【问题标题】:Problems with Java regular expressionsJava正则表达式的问题
【发布时间】:2014-03-16 19:38:38
【问题描述】:

我似乎无法使用正则表达式获得我想要的文本。

我需要用“...from...to...”分隔的文本

示例输入:

text1 from text2 to text3

我当前的代码:

String[] word=input.split("from|to",3);

System.out.println("Text 1: "+word[0]);
System.out.println("Text 2: "+word[1]);
System.out.println("Text 3: "+word[2]);

如果我想忽略 Text1 中的单词 '..from..to..' 并且只使用 '...from..to..',我可以如何改进此代码的任何想法,这是最后一次出现(即 text2 和 text3)

例子:

from here to China will take you from 10 to 12 hours.

我想要文字:

  • text1: from here to China will take you 一个句子
  • 文本2:10
  • 文本3:12 hours

【问题讨论】:

  • 那么问题出在哪里?比“我被卡住了”更具体。
  • 也许尝试在之前添加这一行:input = input.replaceAll("\\s+", "");
  • 这个问题似乎是题外话,因为它是关于审查代码的,这是在Code Review的主题
  • @SimonAndréForsberg 如果这段代码不起作用(“我似乎无法获得我想要的文本”),那么它是not -代码审查的主题!如果以后清楚该代码实际上按预期工作,您可以将其标记为迁移。
  • @amon 抱歉,问题已被编辑。确实正确,这个问题不是关于 CR 的主题。

标签: java regex split


【解决方案1】:

这将像您的示例一样拆分您的短语:

String input = "from here to China will take you from 10 to 12 hours";
System.out.println(Arrays.toString(input.split("\\bfrom\\b\\s+(?=\\d)|\\bto\\b\\s+(?=\\d)")));

在 split 方法中简单地使用from|to 的问题是您的短语包含fromto 的多次出现。因此,在这种情况下,有必要指定您只需要fromto,后跟空格和数字。还添加了单词边界\\b 以仅匹配to 单词而不匹配包含to 的单词,例如toronto


所以你可以像这样调整你的代码:

String[] word=input.split("\\bfrom\\b\\s+(?=\\d)|\\bto\\b\\s+(?=\\d)");

System.out.println("Text 1: "+word[0]);

System.out.println("Text 2: "+word[1]);

System.out.println("Text 3: "+word[2]);

更新:正则表达式实际上可以简化为:

\\b(from|to)\\b\\s+(?=\\d)

【讨论】:

    【解决方案2】:

    String split() 不会帮助你达到这个目的。您必须使用模式匹配。看这个例子:

    String text = "from here to China will take you from 10 to 12 hours";
    Pattern pattern = Pattern.compile("\\b(from\\s+.*?)\\s+from\\s+(\\d+)\\s+to\\s+(\\d+\\s+hours?)\\b");
    
    Matcher m = pattern.matcher(text);
    if (m.find()) {
        System.out.println(m.group(1));
        System.out.println(m.group(2));
        System.out.println(m.group(3));
    }
    

    如果您的字符串的格式发生其他任何变化,这将不起作用。

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 2011-04-25
      相关资源
      最近更新 更多