简体   繁体   中英

How to match a String having metacharacters using regex matches function in Java

What could be the regular expression to match below String

String str = "<Element>\r\n <Sub>regular</Sub></Element>";

There is a

carriage return "\r", new line character "\n" and a space after <Element>.

My code is as below

if(str.matches("<Element>([\\s])<Sub>(.*)"))
{
     System.out.println("Matches");
}

Use the "dot matches newline" switch:

if (str.matches("(?s)<Element>\\s*<Sub>(.*)"))

With the switch turned on, \\s will match newline characters.

I slso fixed your regex, removing two sets of redundant brackets, and adding the crucial * after the whitespace regex.

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