简体   繁体   中英

How to match the beginning of a String in Java?

I want to match an HTML file:

If the file starts with spaces and then an end tag </sometag> , return true .

Else return false .

I used the "(\\\\s)*</(\\\\w)*>.*" , but it doesn't match \\n </p>\\n </blockquote> ... .

Thanks to Gabe's help. Gabe is correct. The . doesn't match \\n by default. I need to set the DOTALL mode on.

To do it, add the (?s) to the beginning of the regex, ie (?s)(\\\\s)*</(\\\\w)*>.* .

You can also do this:

Pattern p = Pattern.compile("(\\s)*</(\\w)*>");
Matcher m = p.matcher(s);
return m.lookingAt();

It just checks if the string starts with the pattern, rather than checking the whole string matches the pattern.

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