在特殊字符之前匹配字符串

use*_*624 1 java regex string char match

我是java的新手,我被困在一个函数上.

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

我想在之前数学文本"<".

例如:

Str[0] = test lala idea
Str[1] = I want potatoes
Run Code Online (Sandbox Code Playgroud)

我尝试使用RegEx但是everythig没有用.所以,如果有人有想法?对不起我的英语技能.谢谢.

ede*_*ora 5

这是一个解决方案:

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

}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,split采用"test lala idea"(从beginnning到第一个'<')并保存在piecesOfTest [0]内(这只是一个解释).然后取"我想要土豆"(从第一个'<'util第二个'<')并将其保存到piecesOfTest 1,所以数组的下一个位置.

如果你想在循环中打印它,你可以按照下面的步骤操作(这个循环应该只在.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]);

}
Run Code Online (Sandbox Code Playgroud)

只是为了学习,正如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);

}
Run Code Online (Sandbox Code Playgroud)

  • 虽然split使用正则表达式并且在正则表达式中确实有些字符是特殊的并且需要被转义,但是```不是其中之一所以`split("<")`在这种情况下完全没问题. (2认同)