0

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:

  • If I don't have multiple lines (e.g. if I only had SYBASE=... followed by the new line), it would match
  • If I evaluate the expression extractorPattern.matcher("SYBASE_OCS=OCS-12_5\\nSYBASE=/opt/sybase/oc12.5.1-EBF12850\\n") (note the double backslash in front of the new line), it would match.
  • I have tried to use variableDefinition.replace("\n", "\\n") to what I give to the matcher(), but it doesn't match.

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the solution as well as for the clear explanation

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.