简体   繁体   中英

How can I keep a while loop going if the string contains a letter

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.

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 (eg [\\\\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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM