【问题标题】:Match string before special char在特殊字符之前匹配字符串
【发布时间】:2014-05-09 07:16:33
【问题描述】:

我是 java 新手,但我被困在一个函数上。

我有一个字符串:"test lala idea<I want potatoes<"

我想计算 "<" 之前的文本。

示例:

Str[0] = test lala idea
Str[1] = I want potatoes

我尝试使用 RegEx,但一切都没有奏效。 那么,如果有人有想法? 对不起我的英语水平。 谢谢。

【问题讨论】:

  • 查看 String 类中的 split() 函数。 Google for Javadocs。
  • 您使用的正则表达式/代码是什么?它可能已经完成了匹配第二个 <.> 之前的所有文本的贪婪匹配

标签: java regex string char match


【解决方案1】:

这是一个解决方案:

public static void main(String [] args)
{
    String test = "test lala idea<I want potatoes<";

    String piecesOfTest[] = test.split("<"); 
    // if you need to split by a dot you need to use "\\."

    System.out.println(piecesOfTest[0]); 
    // prints "test lala idea"
    System.out.println(piecesOfTest[1]); 
    // prints "I want potatoes"

    // Here goes a for loop in case you want to 
    // print the array position by position

}

在这种情况下, split 采用“test lala idea”(从开始到第一个')并保存在piecesOfTest[0]中(这只是一个解释)。然后获取“我想要土豆”(从第一个 ')并将其保存到piecesOfTest1,因此数组的下一个位置.

如果您想在循环中打印此内容,您可以按照以下步骤操作(此循环应仅在运行 .split(regex) 之后放置:

for(int i = 0; i < piecesOfTest.length; i++){

  // 'i' works as an index, so it will be run for i=0, and i=1, due to the condition 
  // (run while) `i < piecesOfTest.length`, in this case piecesOfTest.length will be 2. 
  // but will never be run for i=2, due to (as I said) the condition of run while i < 2

  System.out.println(piecesOfTest[i]);

}

只是为了学习,正如ambigram_maker 所说,您还可以使用“for each”结构:

for (String element: piecesOfTest)

    // for each loop, each position of the array is stored inside element
    // So in the first loop piecesOfTest[0] will be stored inside element, for the
    // second loop piecesOfTest[1] will be stored inside element, and so on

    System.out.println(element);

}

【讨论】:

  • 谢谢 :D 但是你有想法在控制台中创建一个循环打印吗? @ederrollora
  • 请把我的回答标记为正确,以便我们结束这个问题。谢谢
  • 或许你应该演示一下for...each循环的用法……现在大家都在用这个!
  • 虽然 split 确实使用了正则表达式,并且在正则表达式中某些字符是特殊的并且需要转义,但 &lt; 不是其中之一,所以 split("&lt;") 在这种情况下非常好。跨度>
  • True Pshemo,例如'-',如果我没记错也可以用作分隔符而无需\\。但例如点'\\.'需要逃脱。我将修改代码并删除 \\,谢谢。
最近更新 更多