2

I have a long string which is of the form:

enter image description here

How can i extract the data between <DETAIL> and </TEXT>, note that its NOT an xml file. There is a new line after every ending. I tried the following :

Pattern pattern = Pattern.compile("<DETAIL>(.*?)</TEXT>");
    Matcher matcher = pattern.matcher(string);
    while (matcher.find()) {
        System.out.println(matcher.group(1));
    }

It gives me null values, any one can help ? Thanks in advance.

2 Answers 2

5

By default, . does not match newline.

Use s flag (DOTALL) to make . match to newline.

Pattern pattern = Pattern.compile("(?s)<DETAIL>(.*?)</TEXT>");

or

Pattern pattern = Pattern.compile("<DETAIL>(.*?)</TEXT>", Pattern.DOTALL);
Sign up to request clarification or add additional context in comments.

5 Comments

+1, other version without not so intuitive (?s): Pattern.compile("<DETAIL>(.*?)</TEXT>", Pattern.DOTALL);
@Pshemo, I add that to the answer. Thank you for comment.
thanks a lot !, is there anyway get the values of the DATE after extracting ? by using another pattern matching or something ? After extracting i get a empty line followed by DATE=1233 in a new line and DAY=Monday in another line,
@parameswar, How about using <DETAIL>.*?DATE=(\d+).*?</TEXT> as patttern?
Thanks again, just had to tweak it a bit, added \S to match a mix of integers and characters
0

Try [\s\S]*? in place of .*?. . does not match new lines.

5 Comments

+0. It will work, but to get rid of this kind of solution there is DOTALL flag (?s).
At least [\s\S] is a solution that works across different languages.
(?s) is not Java only flag.
Yet it doesn't work in JavaScript and the flag is not the same across most languages.
OK. You have got the point about JS. You need to use something like [\s\S] or [\d\D] there to simulate DOTALL behaviour, but if you can use this flag instead you should. This will make your regex easier to read which means also easier to maintain.

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.