Matteo NNZ
Matteo NNZ

Reputation: 12665

Cannot match string with regex pattern when such string is done of multiple lines

I have a string like the following:

SYBASE_OCS=OCS-12_5
SYBASE=/opt/sybase/oc12.5.1-EBF12850
//there is a newline here as well

The string at the debugger appears like this:

enter image description here

I am trying to match the part coming after SYBASE=, meaning I'm trying to match /opt/sybase/oc12.5.1-EBF12850.

To do that, I've written the following code:

String key = "SYBASE";
Pattern extractorPattern = Pattern.compile("^" + key + "=(.+)$");
Matcher matcher = extractorPattern.matcher(variableDefinition);
if (matcher.find()) {
    return matcher.group(1);
}

The problem I'm having is that this string on 2 lines is not matched by my regex, even if the same regex seems to work fine on regex 101.

State of my tests:

It seems something simple but I can't get out of it. Can anyone please help?

Note: the string in that format is returned by a shell command, I can't really change the way it gets returned.

Upvotes: 0

Views: 37

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47099

The anchors ^ and $ anchors the match to the start and end of the input.

In your case you would like to match the start and end of a line within the input string. To do this you'll need to change the behavior of these anchors. This can be done by using the multi line flag.

Either by specifying it as an argument to Pattern.compile:

Pattern.compile("regex", Pattern.MULTILINE)

Or by using the embedded flag expression: (?m):

Pattern.compile("(?m)^" + key + "=(.+)$");

The reason it seemed to work in regex101.com is that they add both the global and multi line flag by default:

Default flags for regex101

Upvotes: 2

Related Questions