solo regulares regular numeros nombre negar letras expresiones expresion excluir especiales espacios distinto crear caracteres apellidos java regex

java - regulares - regex caracteres especiales c#



¿Cómo hacer coincidir letras solo utilizando regex java, método de coincidencias? (5)

Tres problemas aquí:

  1. Solo usa String.matches() - si la API está ahí, String.matches()
  2. En java, "coincidencias" significa "coincide con toda la entrada", cuyo IMHO es contraintuitivo, así que permita que la API de su método refleje eso al permitir que las personas que llaman piensen en hacer coincidir una parte de la entrada como sugiere su ejemplo
  3. Tu expresión regular solo coincide con 1 personaje.

Te recomiendo que uses un código como este:

public boolean matches(String regex) { regex = "^.*" + regex + ".*$"; // pad with regex to allow partial matching System.out.println("abcABC ".matches(regex)); return "abcABC ".matches(regex); } public static void main(String[] args) { HowEasy words = new HowEasy(); words.matches("[a-zA-Z]+"); // added "+" (ie 1-to-n of) to character class }

import java.util.regex.Pattern; class HowEasy { public boolean matches(String regex) { System.out.println(Pattern.matches(regex, "abcABC ")); return Pattern.matches(regex, "abcABC"); } public static void main(String[] args) { HowEasy words = new HowEasy(); words.matches("[a-zA-Z]"); } }

La salida es falsa. ¿A dónde me voy mal? También quiero verificar si una palabra contiene solo letras y puede o no terminar con un solo período. ¿Cuál es la expresión regular para eso?

es decir "abc" "abc". es válido pero "abc .." no es válido.

Puedo usar el método indexOf() para resolverlo, pero quiero saber si es posible usar una sola expresión regular.


"[a-zA-Z]" solo coincide con un carácter. Para hacer coincidir varios caracteres, use "[a-zA-Z]+" .

Como un punto es un comodín para cualquier personaje, debes enmascararlo: "abc/." Para hacer que el punto sea opcional, necesita un signo de interrogación: "abc/.?"

Si escribe el Patrón como constante literal en su código, debe enmascarar la barra invertida:

System.out.println ("abc".matches ("abc//.?")); System.out.println ("abc.".matches ("abc//.?")); System.out.println ("abc..".matches ("abc//.?"));

Combinando ambos patrones:

System.out.println ("abc.".matches ("[a-zA-Z]+//.?"));

En lugar de a-zA-Z, / w suele ser más apropiado, ya que captura caracteres extranjeros como äöüßø y así sucesivamente:

System.out.println ("abc.".matches ("//w+//.?"));


[A-Za-z ]* para hacer coincidir letras y espacios.


matches método de coincidencias realiza una comparación de línea completa, es decir, es equivalente a find() con ''^ abc $''. Entonces, solo use Pattern.compile("[a-zA-Z]").matcher(str).find() lugar. Entonces arregla tu expresión regular. Como @user unknown mencionó, tu expresión regular solo coincide con un personaje. Probablemente deberías decir [a-zA-Z]+


import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.*; /* Write an application that prompts the user for a String that contains at least * five letters and at least five digits. Continuously re-prompt the user until a * valid String is entered. Display a message indicating whether the user was * successful or did not enter enough digits, letters, or both. */ public class FiveLettersAndDigits { private static String readIn() { // read input from stdin StringBuilder sb = new StringBuilder(); int c = 0; try { // do not use try-with-resources. We don''t want to close the stdin stream BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while ((c = reader.read()) != 0) { // read all characters until null // We don''t want new lines, although we must consume them. if (c != 13 && c != 10) { sb.append((char) c); } else { break; // break on new line (or else the loop won''t terminate) } } // reader.readLine(); // get the trailing new line } catch (IOException ex) { System.err.println("Failed to read user input!"); ex.printStackTrace(System.err); } return sb.toString().trim(); } /** * Check the given input against a pattern * * @return the number of matches */ private static int getitemCount(String input, String pattern) { int count = 0; try { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(input); while (m.find()) { // count the number of times the pattern matches count++; } } catch (PatternSyntaxException ex) { System.err.println("Failed to test input String /"" + input + "/" for matches to pattern /"" + pattern + "/"!"); ex.printStackTrace(System.err); } return count; } private static String reprompt() { System.out.print("Entered input is invalid! Please enter five letters and five digits in any order: "); String in = readIn(); return in; } public static void main(String[] args) { int letters = 0, digits = 0; String in = null; System.out.print("Please enter five letters and five digits in any order: "); in = readIn(); while (letters < 5 || digits < 5) { // will keep occuring until the user enters sufficient input if (null != in && in.length() > 9) { // must be at least 10 chars long in order to contain both // count the letters and numbers. If there are enough, this loop won''t happen again. letters = getitemCount(in, "[A-Za-z]"); digits = getitemCount(in, "[0-9]"); if (letters < 5 || digits < 5) { in = reprompt(); // reset in case we need to go around again. } } else { in = reprompt(); } } } }