Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search on a particular line using Regular Expression in Java

Tags:

java

regex

I am new with Regular Expression and might be my question is very basic one.

I want to create a regular expression that can search an expression on a particular line number.

eg. I have data

"\nerferf erferfre erferf 12545" + 
"\ndsf erf" + 
"\nsdsfd refrf refref" + 
"\nerferf erferfre erferf 12545" + 
"\ndsf erf" + 
"\nsdsfd refrf refref" + 
"\nerferf erferfre erferf 12545" + 
"\ndsf erf" + 
"\nsdsfd refrf refref" + 
"\nerferf erferfre erferf 12545" + 

And I want to search the number 1234 on 7th Line. It may or may not be present on other lines also.

I have tried with

"\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\d{4}" 

but am not getting the result.

Please help me out with the regular expression.

like image 812
Nitesh Gupta Avatar asked Apr 22 '13 10:04

Nitesh Gupta


2 Answers

Firstly, your newline character should be placed at the end of the lines. That way, picturing a particular line would be easier. Below explanation is based on this modification.

Now, to get to 7th line, you would first need to skip the first 6 line, that you can do with {n,m} quantifier. You don't need to write .*\n 6 times. So, that would be like this:

(.*\n){6}

And then you are at 7th line, where you can match your required digit. That part would be something like this:

.*?1234

And then match rest of the text, using .*

So, your final regex would look like:

(?s)(.*\n){6}.*?1234.*

So, just use String#matches(regex) method with this regex.

P.S. (?s) is used to enable single-line matching. Since dot(.) by default, does not matches the newline character.

To print something you matched, you can use capture groups:

(?s)(?:.*\n){6}.*?(1234).*

This will capture 1234 if matched in group 1. Although it seems unusual, that you capture an exact string that you are matching - like capturing 1234 is no sense here, as you know you are matching 1234, and not against \\d, in which case you might be interested in exactly what are those digits.

like image 114
Rohit Jain Avatar answered Oct 05 '22 13:10

Rohit Jain


Try

Pattern p = Pattern.compile("^(\\n.*){6}\\n.*\\d{4}" );
System.out.println(p.matcher(s).find());
like image 23
Arun P Johny Avatar answered Oct 05 '22 11:10

Arun P Johny