bob
bob

Reputation: 61

Java regex between 2 characters include new line or tab

I have a problem with regex between 2 strings. I want get value between string # and # but this regex is not working when I have a new line (in my case \r\n). for example:

#89899#
#this is string I have
problem#

I have a problem with line 2 because have new line. how to exclude new line in regex? my code:

public static List parserStringBetween(String param1, String param2, String data) {
    List result = null;

    if (param1 != null && !"".equalsIgnoreCase(param1) && param2 != null && !"".equalsIgnoreCase(param2)
            && data != null && !"".equalsIgnoreCase(data)) {
        result = new ArrayList<>();
        Matcher m = Pattern.compile("\\" + param1 + "(.*?)\\" + param2).matcher(data);
        while (m.find()) {
            result.add(m.group(1));
        }

    }
    return result;
}

param1 and param2 are string between setting i.e # here. How to solve this problem?

Upvotes: 1

Views: 262

Answers (2)

Shanu Gupta
Shanu Gupta

Reputation: 3807

To include newline and spaces as well, use:

^#[\s\S]*#$

Check it out here in action.

You java code becomes:

Matcher m = Pattern.compile("^" + param1 + "[\\s\\S]*" + param2 + "$").matcher(data);

You can also use Pattern.DOTALL mode as well.

Matcher m = Pattern.compile("\\" + param1 + "(.*?)\\" + param2, Pattern.DOTALL).matcher(data);

Upvotes: 1

Bohemian
Bohemian

Reputation: 425128

Add the DOTALL flag via (?s):

Pattern.compile("\\Q" + param1 + "\\E(?s)(.*?)\\Q" + param2 + "\\E")

Note also the use of \Q...\E to correctly escape the delimiter. Just putting a backslash before it won’t work for all cases.

Upvotes: 2

Related Questions