Home > Back-end >  How do I process different delimiters in a RegEx expression with Java?
How do I process different delimiters in a RegEx expression with Java?

Time:09-20

I am working on creating a program for my course, in which I am required to divide the string: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;.

In the requirements, I need to read a single semicolon as a space, and a double semicolon as a new line. How do I create a regular expression in the useDelimiter() method that allows me to parse through and differentiate between both ; and ;;? Thank you!

Assignment Excerpt: Instead of hard-coding the string, this time you will read it from the console. Study the useDelimiter() method and use it to set the delimiter for the scanner input. This time allow either colons or semicolons as the delimiters. One might prefer to use the String Tokenizer here, but don’t -- use the Scanner’s useDelimiter() method to set the delimiter in the Scanner and process each token as it comes.

import java.util.Scanner;

public class Hw3p2 {
    public static void main(String[] args) {
        // Initializes scanner class.
        Scanner input = new Scanner(System.in);

        // Prompts user for input.
        System.out.println("Enter the string you wish to filter & parse: ");

        // Reads user input.
        String filterString = input.nextLine();

        // Initiates new scanner reading the user inputted string.
        Scanner a = new Scanner(filterString);

        a.useDelimiter(";|;;");

        System.out.printf("\n");

        // Loop that parses through string while there are more tokens.
        while(a.hasNext()) {
            System.out.print(a.next());
        }
    }
}

The Expected output is to be:

Code output

CodePudding user response:

You may use this code:

public class Hw3p2 {
    public static void main(String[] args) {
        // Initializes scanner class.
        Scanner input = new Scanner(System.in).useDelimiter(";;");

        // Prompts user for input.
        System.out.print("Enter the string you wish to filter & parse: ");

        // Reads user input.
        while(input.hasNext()) {
            String filterString = input.next();
            //System.err.println("filterString: "   filterString);

            // Initiates new scanner reading the user inputted string.
            Scanner a = new Scanner(filterString).useDelimiter(";");

            // Loop that parses through string while there are more tokens.
            while(a.hasNext()) {
                System.out.print(a.next()   " ");
            }
            System.out.println();
            a.close();
        }

        input.close();
    }
}

Output:

Enter the string you wish to filter & parse: This;is;the;first;line;;This;is;the;second;line!;;;;Done!;;
This is the first line 
This is the second line! 

Done!

Note use of outer scanner with delimiter ;; and an inner one with ;.

  • Related