3
while (firstName.//includes a,b,c,d,e,f,g.etc)
{
  //other code here
}

I want the while loop to keep going if it includes a letter, please help.

  • You kind of can't. To determine if a string contains a letter, you have to search the whole string. So you might as well just loop over the whole string, period, for whatever you have to do with the string. (I guess what's I'm saying is that you can, but it's redundant and wasteful. So maybe let us know what you are really trying to do, so we can help you better.) – markspace Feb 16 '20 at 23:01

2 Answers2

0

Use .*?[\\p{L}].* as the regex.

If you are sure that your text is purely in English, you can use .*?[A-Za-z].* or .*?[\\p{Alpha}].* alternatively.

Explanation:

  1. .*? looks reluctantly for any character until it yields to another pattern (e.g. [\\p{L}] in this case).
  2. [\\p{L}] looks for a single letter because of [] around \\p{L} where \\p{L} specifies any letter (including unicode).
  3. .* looks for any character.

Demo:

public class Main {
    public static void main(String[] args) {
        String[] arr = { "123a", "a123", "abc", "123", "123a456", "123ß456" };
        for (String firstName : arr) {
            if (firstName.matches(".*?[\\p{L}].*")) {
                System.out.println(firstName + " meets the criteria.");
            }
        }
    }
}

Output:

123a meets the criteria.
a123 meets the criteria.
abc meets the criteria.
123a456 meets the criteria.
123ß456 meets the criteria.

Note that if .*?[A-Za-z].* is used, 123ß456 won't meet the criteria because ß is not part of English alphabets.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Only matches if the string contains one and only one letter, n nothing else. – FredK Feb 16 '20 at 22:56
  • Still not right. "999h999" fails your test, but passes the OP's criterion that it contains at least one letter. – FredK Feb 16 '20 at 22:58
0

Try firstName.matches(matches(".*[A-Za-z].*"));

FredK
  • 4,094
  • 1
  • 9
  • 11