0

I am trying to split a string using a regex "A.*B", which works just fine to retrieve strings between 'A' and 'B'. But the dot '.' doesn't include new line characters \n,\r. Can you please guide me on how to achieve this?

Thanks


Thanks all. Pattern.DOTALL worked like a charm.

I had another question related to this. What should be done if I need to extract all the strings between 'A' and 'B' (which basically match the above regex).

I tried using find() and group() of matcher class, but with the pattern below it seems to return the whole string.

Pattern p = Pattern.compile("A.*B",Pattern.DOTALL);

1
  • 1
    does A[.\n\r]*B work ? Commented Mar 14, 2012 at 11:27

6 Answers 6

1

Use a java.util.regex.Pattern with the MULTILINE flag:

import java.util.regex.Pattern;

Pattern pattern = Pattern.compile("A.*B", Pattern.MULTILINE);
pattern.split(string);
Sign up to request clarification or add additional context in comments.

Comments

1

Compile the regex with this option: Pattern regex = Pattern.compile("A.*B",Pattern.DOTALL)

Comments

1

Try "A[.\\s]*B"

Or you may specify the DOTALL switch so that "." will include even line terminators. Take a look ať the documentation of the Pattern class.

Comments

0

Have a look at java.util.regex.Pattern.compile(String regex, int flags), esp. the DOTALL flag

Comments

0

I assume you use the Pattern, Matcher classes for this.

Have you tried providing MULTILINE to your Pattern.compile() method?

Pattern.compile(regex, Pattern.MULTILINE)

'.' = Any character (may or may not match line terminators)

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html#lt

Comments

0

Try changing yor regex to "A(.|\\s)*B" This means A followed by any character(.) or any white character(\s) any number of times followed by B (double scaped \s is needed at java Code).

Reference for Regular Expressions (constructs, spacial characters, etc.) in Java: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.