简体   繁体   中英

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:

在此处输入图像描述

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 (eg 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.

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:

regex101 的默认标志

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM