1

I´m not a programmer, so my level is newie in this field. I must create a regular expression to check two lines. Between these two lines A and B could be one, two or more different lines.

I´ve been reviewing link http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html but i´ve not reach the solution, althouth i think that i´m very close to the solution.

I am testing the expression ^(.*$) and this gets an entire line. If i write this expression twice it gets two lines. So it seems that this expression is getting as entire lines as occurrences of the expression.

But, i would like to check undetermined lines between A and B. I know that at least it will be one line If i write ^(.*$){1,} it doesn´t work.

Anyone knows which could be the mistake?

Thank you for your time Andres

1
  • Regexes is what you need. Commented Apr 24, 2013 at 10:49

4 Answers 4

1

DOT . in regex matches any character except newline character.

You're looking for DOTALL or s flag here that makes dot match any character including newline character as well. So if you want to match all the lines between literals A and B then use this regex:

(?s)A.*?B

(?s) is for DOTALL that will make .*? match all the characters including newline characters between A and B.

? is to make above regex non-greedy.

Read More: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you use Scanner ? It might be more related to what you want:

Scanner sc = new ...
while (sc.nextLine().compareTo(strB)!=0) {
whatYouWantToDo
}

1 Comment

Hi, is it inside java.util.regex Class Pattern?. I think that "my" application that will check the pattern only understand regular expressions based on this java class.
0

You could try to search for line terminators \r and \n. Depending on the source of the file you maybe have to experiment a bit. As far as I understood it, you want to match the lines, with at least one empty line in between? Try ^(.*)$\n{2,}^(.*)$

Comments

0

If you want to find two equal lines, using regex:

Pattern pattern = Pattern.compile("^(?:.*\n)*(.*\n)(?:.*\n)*\\1");
// Skip some lines, find a line, skip some lines, find the first group `(...)`
Matcher m = pattern.matcher(text);
while (m.find()) {
    System.out.println("Double: " + m.group(1);
}

The (?: ...) is a non-capturing group; that is, not available through m.group(#).

However this won't find line B in: "A\nB\nA\nB\n".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.