0

I'll start with an example:

Assuming the following input (assume that \n is a line break):

MY STRING content1 \n content1; my string content2 \n \n content2; my string content3 content3 \n content3

As you can see, the first two parts end with a ';' character, but the last one doesn't. The following regex pattern match will fetch both first parts, but not the second part:

Matcher m = Pattern.compile("(MY STRING(.*?)\\;)|(my string(.*?)\\;)").matcher(str);

The result is:

MY STRING content1 \n content1;
my string content2 \n \n content2;

But I didn't get:

my string content3 content3 \n content3

Is there a way to match a string that ends with either ";" or when the entire string ends (like the last part)?

Tom Shir
  • 462
  • 1
  • 3
  • 14
  • `Pattern.compile(pattern, Pattern.DOTALL)` – Wiktor Stribiżew Apr 26 '18 at 07:25
  • 1
    regex placeholder character for end of line is `$`, try to replace your `\\;` by `(\\;|$)`. By the way, is escaping `;` mandatory in java regex? – Kaddath Apr 26 '18 at 07:27
  • @Kaddath, worked perfectly, thank you! Not sure about whether the escaping is required, will look into that. – Tom Shir Apr 26 '18 at 07:32
  • @WiktorStribiżew, this question isn't a duplicate of the question you mentioned. The solution is different, as the problem is different. – Tom Shir Apr 26 '18 at 12:22
  • You say `\n` is a line break, thus, without `Pattern.DOTALL`, even `(;|$)` won't help. Besides, the best solution here is `Pattern.compile("(MY STRING([^;]*))", Pattern.CASE_INSENSITIVE)`. Not sure you really need that many groups here. `[^;]` matches any chars other than `;` including line breaks. – Wiktor Stribiżew Apr 26 '18 at 12:41

0 Answers0