Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match some pattern with line break

Tags:

java

regex

I want to write regEx to match following pattern:

From: ***********************
Sent: ***********************
To: ***********************
Subject: *******************

I wrote regEx as

.*From:.+(\n)Sent:.+(\n)To:.+(\n)Subject:.+(\n).*

But this is not working. Kindly help me as I am new to regEx.

like image 723
slayer Avatar asked Feb 23 '16 07:02

slayer


People also ask

What is the use of \\ in RegEx?

You also need to use regex \\ to match "\" (back-slash). Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

How do you match a pattern to a string?

To match a character in the string expression against a list of characters. Put brackets ( [ ] ) in the pattern string, and inside the brackets put the list of characters.

How do I match any character across multiple lines in a regular expression?

The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.


1 Answers

Your regex does not work because of two possible reasons:

  • The newline sequence can be \r\n, or \r, or \n (or even more, \u000B, \u000C, \u0085, \u2028 or \u2029), but you only coded in the LF. Adding an optional CR (carriage return, \r) can help.
  • Also, after Subject:..., there is no newline, so you need to remove it.
  • In Java 8+, there is a special line break shorthand class, \R, that you may use to match any line break sequence.

You can use

From:.+\r?\nSent:.+\r?\nTo:.+\r?\nSubject:.+
From:.+\RSent:.+\RTo:.+\RSubject:.+

Search for a partial match with Matcher#find().

See the regex demo

And the IDEONE demo:

String p = "From:.+\r?\nSent:.+\r?\nTo:.+\r?\nSubject:.+"; 
// String p = "From:.+\\RSent:.+\\RTo:.+\\RSubject:.+";  // Java 8+ compliant
String s = "Some text before.....\r\nFrom: ***********************\r\nSent: ***********************\r\nTo: ***********************\r\nSubject: *******************"; 
Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(0)); 
} 
like image 150
Wiktor Stribiżew Avatar answered Sep 20 '22 13:09

Wiktor Stribiżew