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.
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.
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.
The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.
Your regex does not work because of two possible reasons:
\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.Subject:...
, there is no newline, so you need to remove it.\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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With