java - 匹配特殊字符前的字符串

标签 java regex string char match

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

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

我想对 "<" 之前的文本进行数学运算.

例子:

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

我尝试使用 RegEx,但没有任何效果。 那么,如果有人有想法? 对不起我的英语技能。 谢谢。

最佳答案

这是一个解决方案:

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”(从 beginnning 到第一个 '<')并保存在 piecesOfTest[0] 中(这只是一个解释)。然后获取“我想要土 bean ”(从第一个“<”到第二个“<”)并将其保存到 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]);

}

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

}

关于java - 匹配特殊字符前的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736350/

相关文章:

java - 正则表达式查找子字符串

regex - SED 中的多行替换

oracle - Oracle中查找字符串的最后一个索引

java - 将 int 数组转换为 String 并返回 (getArrayString)

string - 如何在 Swift 中将字符串替换为字符串?

java - EJB 无法解析引用,因为应用程序中存在多个具有相同接口(interface)的 ejb

java - Java、C++、Python 和 ObjC 的在线编译器/运行时?

java - 在他们登录我的网站/应用程序后,我如何请求 Facebook 权限?

java - Android Tooltip 菜单项样式

javascript - JS XRegExp 替换所有非字符