如何在大字符串中首次出现单词并在分隔符

时间:2017-08-30 19:46:45

标签: java

我有一个字符串

abc: text||something mnamed||abc:text2||something name2||abc:text3

我希望在第一次出现此字符串时打印分隔符之间的值" abc:" 我们可以在这里看到abc:在字符串中出现3次,但我希望数据在第一次出现在该字符串中时 对于上面的例子,我的输出应该是======>> abc: text FOR

something mnamed||abc:text2||something name2||abc: text||something name2||abc:text3 

输出应为=====>> abc:text2 FOR

   something mnamed||something name2||abc:text3||abc:text2||something mnamed
output should be=======>> abc:text3

2 个答案:

答案 0 :(得分:0)

我按||分割字符串,过滤以abc:开头的子字符串并取第一个字符串:

String str = "something mnamed||abc:text2||something name2||etc...";
String result = 
    Arrays.stream(str.split("\\|\\|"))
          .filter(s -> s.startsWith("abc:"))
          .findFirst()
          .orElse(null);

答案 1 :(得分:0)

Although there are many valid approaches for solving this problem, using regular expression is probably among the most expedient ones.

Start by looking for an occurrence of select() followed by a sequence that terminates in starts_with, or reaches the end of the input. Capturing this sequence produces the desired result.

The only tricky issue here is finding double bars one_of while allowing single bars "abc:" inside the text. This can be done by the following expression: ||

Demo.

Using the expression above with Java regex library is left to the reader as a straightforward learning exercise.