-2

Working on a Java program that can grab words from a text doc that start with "A" and are 7 letters longer. I am trying to use Regular Expressions in Java.

Might someone give me some pointers here how to do this?

`Pattern sevenLetters = Pattern.compile("^\\w{A}{6}$");`

Does not obtain what I'm aiming for unfortunately.

What is the syntax that goes into the ()?

Thanks

Katie Melosto
  • 411
  • 2
  • 8

1 Answers1

1

Maybe,

\\bA[a-z]{6}\\b

might simply work OK.

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){


        final String regex = "\\bA[a-z]{6}\\b";
        final String string = "Aabcdef Aabcdefg Aabcde Aabcdef \n"
             + "Aabcdef Aabcdefg Aabcde Aabcdef ";

        final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Community
  • 1
  • 1
Emma
  • 1
  • 9
  • 28
  • 53