-2

Pattern: ([^\|]*)

Strings:

  1. They found the the huge gold in Vietnam|China|Lao last summer. | BBCworld.com
  2. They found the the huge gold in Vietnam|China|Lao last summer.

Result: They found the the huge gold in Vietnam

Demo: http://regexr.com/3f8hi

Target:

They found the the huge gold in Vietnam|China|Lao last summer.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
user3522582
  • 35
  • 1
  • 4
  • Question: How do you know it is OK to remove " | BBCworld.com" from string 1 but not OK to remove "|Lao last summer." from string 2? You must answer that question before we can answer your question. – Patrick Parker Feb 09 '17 at 10:46
  • P.S. @WiktorStribiżew it's not a duplicate, just poorly worded and poorly defined. – Patrick Parker Feb 09 '17 at 10:48

2 Answers2

2

A classic case of using regex where it's not needed:

String result = input.substring(0, input.lastIndexOf('|'));
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • I would say `indexOf`: The example says That for `They found the the huge gold in Vietnam|China|Lao last summer. | BBCworld.com` and `They found the the huge gold in Vietnam|China|Lao last summer.` the result should be `They found the the huge gold in Vietnam`, so it's the very first index of `|`, not the last one. – BackSlash Feb 09 '17 at 10:39
  • @BackSlash but the *desired output* is "They found the the huge gold in Vietnam|China|Lao last summer.". – Andy Turner Feb 09 '17 at 10:39
  • Oh. So "Result" is what he is getting and "Target" is what he wants to achieve... My bad, but OP could have explained a little bit better. Sorry! – BackSlash Feb 09 '17 at 10:41
  • @BackSlash no problem, it's not very clear. – Andy Turner Feb 09 '17 at 10:41
0

Use the $ anchor, that means end of string:

\|[^|]*$
Toto
  • 89,455
  • 62
  • 89
  • 125