user3736846
user3736846

Reputation: 5

How can I make a Regex that will match only alpha characters?

I am trying to split a sentence into words and then print them if they contain only alpha characters. Other characters should output an error message instead.

Example Input:

The quick brown fox

Desried Output:

The

quick

brown

fox

Example Input:

Th1 qu1ck br0wn fox

Desired Output:

This is invalid.

I trried to do this using pattern but I think it didn't work.

import java.util.Scanner;
import java.util.regex.Pattern;
public class test {

    public static void main(String[] args) {

        System.out.println("This will break a sentence into words.");
        Scanner alpha = new Scanner(System.in);
        String beta = alpha.nextLine();
        String [] data = beta.split(" ");
        if (Pattern.matches("[a-zA-Z]+", beta)){
            System.out.println(data[0]);
            System.out.println(data[1]);
            System.out.println(data[2]);
            System.out.println(data[3]);
        }
        else {
            System.out.println("This is not valid.");
        }
    }

}

Upvotes: 0

Views: 493

Answers (5)

user902383
user902383

Reputation: 8640

try this:

   System.out.println("This will break a sentence into words.");
        Scanner alpha = new Scanner(System.in);
        String beta = alpha.nextLine();
        String [] data = beta.split("\\s+");
        boolean valid = true;
        for (String word: data)
        if (!Pattern.matches("[a-zA-Z]+", word)){
               valid = false
                break;
         }
         if(valid)
        System.out.println("This is valid.");
            else
        System.out.println("This is not valid.");

small tweaks if your word contains more tnat standards 26 letters

String beta = "Dieser Satz ist ungültig. This is valid";
String[] data = beta.split("[\\s+|\\.+]+");
boolean valid = true;

a: for (String word : data)
    for (char c : word.toCharArray())
        if (!Character.isAlphabetic(c)) {
            valid = false;
            break a;
        }

 if(valid)
       for (String word : data)
           System.out.println(word);
   else
        System.out.println("This is not valid.");

Upvotes: 0

Rubinum
Rubinum

Reputation: 557

The answer is easy :). You tried to match your pattern with the whole inputString "beta", but you splitted the "beta" already and you want to match the pattern not with beta, but with one element of your array "data".

Change this:

if (Pattern.matches("[a-zA-Z]+", beta)){}

to this:

for(String word : data)
{
  Pattern.matches("[a-zA-Z]+", word)
}

You have to handle the situation where the pattern not match, but thats your work. :) I hope it helps.

Upvotes: 2

BSeitkazin
BSeitkazin

Reputation: 3059

If I understand a question, the simple way is to check the letters with ASCII code:

public class Test {

    public static void main(String[] args) {
        System.out.println("This will break a sentence into words.");
        Scanner alpha = new Scanner(System.in);
        String beta = alpha.nextLine();
        int count = 0;
        for (int i=0; i<beta.length(); i++) {
            if (((int)beta.charAt(i) > 64 && (int)beta.charAt(i) < 91) || ((int)beta.charAt(i) > 96 && (int)beta.charAt(i) < 123) || ((int)beta.charAt(i) == 32)) {
                count++;
            }
        }

        if (count == beta.length()) {
            System.out.println("correct");
        } else {
            System.out.println("incorrect");
        }
    }
}

Upvotes: 0

udalmik
udalmik

Reputation: 7988

One more option with checking the whole line before parsing the words:

 private static boolean isValidSymbols(String s) {
    return  s != null && s.matches("[a-zA-Z\\s]+");
 }

 private static void checkInput(String s) {
     if (isValidSymbols(s)) {
         for (String word : s.split("\\s+")) {
             System.out.println(word);
         }
     } else {
         System.out.println("This is not valid.");
     }
 }

 public static void main(String[] args) {
     checkInput("The quick brown fox");
     checkInput("Th1 quick br0wn fox");
 }

Upvotes: 0

HJK
HJK

Reputation: 1382

Try the following code:

    String str = "This is a brown fox";
    String patternStr= "[0-9]{1}";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(str);
    if(matcher.find()){
      System.out.println("invalid");
    }else{
        System.out.println("valid");
    }

Thanks, JK

Upvotes: -1

Related Questions