Results 1 to 2 of 2

Thread: Java, Regex and linebreaks

  1. #1
    Join Date
    Dec 2011

    Java, Regex and linebreaks

    I am new to Regular expressions, so I am trying to figure this out. I wrote in a plain .txt file in Notepad:

    Description1 This is a test of a description. Yay Description2.

    I then used this regex in order to search and return the text between (But not including) the words Description1 and Description2


    It works just as intended. But now I need to find a way for the regex to read linebreaks, so if the description is written like this:

    Description1 This is a test of
    a description. Yay Description2.

    It will still return what I want it too. Ive done research, a lot of people say the same thing. Do Pattern.MULTILINE or Pattern.DOTALL, as well as adding (?S) at the beginning of the expression (In this case likely before the .*), or/and typing [\n\r] or something similar. I've tried many combinations of these things and nothing seems to work, it always says there is no match. Any help would be appreciated.

  2. #2
    Join Date
    Dec 2011
    Here is the code I am using by the way. It is mostly taken from a homework assignment, but I am altering it for a personal project I am starting.

    import java.util.Scanner;
    import javax.swing.*;
    import java.util.regex.*;
    public class SearchTest {
    	 * @param args
    	public static void main(String[] args) throws Exception {
    		String name = (String)JOptionPane.showInputDialog(null, "Enter Pokemon Name");
    		String cleanName = name.toLowerCase().trim();
    		String filename = null;
    		if(cleanName.equals("bulbasaur") || cleanName.equals("1") 
    				|| cleanName.equals("01") || cleanName.equals("001")) {
    			filename = "src\\\\bulbasaur2.txt";
    		} else if (cleanName.equals("charmander") || cleanName.equals("2")
    				|| cleanName.equals("02") || cleanName.equals("002")) {
    			filename = "src\\\\charmander.txt";
    		java.io.File file = new java.io.File(filename);
    		Scanner input = new Scanner(file);
    		String patternString = "(?s)(?<=Description1\\s).*?(?=\\sDescription2)";
    		Pattern pattern = Pattern.compile(patternString, Pattern.DOTALL);
    		int count = 0;
    		while(input.hasNext()) {
    			String input2 = input.nextLine();
    			Matcher matcher = pattern.matcher(input2);
    			while(matcher.find()) {
    				int start = matcher.start();
    				int end = matcher.end();
    				String match = input2.substring(start,end);
    				System.out.println(match + " Start " + start + " End " + end);
    		System.out.println("There are " + count + " matches.");

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center