limitar caracteres java regex javafx textfield

limitar caracteres jtextfield java



Cómo restringir TextField para que pueda contener solo un ''.'' ¿personaje? JavaFX (3)

En Internet, encontré una clase muy útil, con la que puedo restringir TextField. Encontré un problema, donde mi TextField puede contener solo un ''.'' personaje. Sospecho que puedo manejar esto escribiendo una expresión regular apropiada y establecerla como una restricción en la instancia de esa clase. Utilizo la siguiente expresión regular: "[0-9.-]", pero permite tantos puntos como los tipos de usuario. Puedo pedirle que me ayude a configurar mi TextField para que no haya más de un ''.'' esta permitido.

import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.TextField; /** * Created by Anton on 7/14/2015. */ public class RestrictiveTextField extends TextField { private IntegerProperty maxLength = new SimpleIntegerProperty(this, "maxLength", -1); private StringProperty restrict = new SimpleStringProperty(this, "restrict"); public RestrictiveTextField() { super("0"); textProperty().addListener(new ChangeListener<String>() { private boolean ignore; @Override public void changed(ObservableValue<? extends String> observableValue, String s, String s1) { if (ignore || s1 == null) return; if (maxLength.get() > -1 && s1.length() > maxLength.get()) { ignore = true; setText(s1.substring(0, maxLength.get())); ignore = false; } if (restrict.get() != null && !restrict.get().equals("") && !s1.matches(restrict.get() + "*")) { ignore = true; setText(s); ignore = false; } } }); } /** * The max length property. * * @return The max length property. */ public IntegerProperty maxLengthProperty() { return maxLength; } /** * Gets the max length of the text field. * * @return The max length. */ public int getMaxLength() { return maxLength.get(); } /** * Sets the max length of the text field. * * @param maxLength The max length. */ public void setMaxLength(int maxLength) { this.maxLength.set(maxLength); } /** * The restrict property. * * @return The restrict property. */ public StringProperty restrictProperty() { return restrict; } /** * Gets a regular expression character class which restricts the user input. * * @return The regular expression. * @see #getRestrict() */ public String getRestrict() { return restrict.get(); } /** * Sets a regular expression character class which restricts the user input. * E.g. [0-9] only allows numeric values. * * @param restrict The regular expression. */ public void setRestrict(String restrict) { this.restrict.set(restrict); }

}


Hay varias versiones de la expresión regular, dependiendo de exactamente lo que quiere apoyar. Tenga en cuenta que no solo desea hacer coincidir números válidos, sino también entradas parciales, porque el usuario debe poder editar esto. Entonces, por ejemplo, una cadena vacía no es un número válido, pero ciertamente quiere que el usuario pueda eliminar todo lo que está allí mientras está editando; de manera similar, quiere permitir "0." , etc.

Entonces probablemente quieras algo como

Signo menos opcional, seguido de cualquier cantidad de dígitos, o al menos un dígito, un punto ( . ) Y cualquier cantidad de dígitos.

La expresión regular para esto podría ser -?((//d*)|(//d+/.//d*)) . Probablemente haya otras maneras de hacerlo, algunas de ellas tal vez más eficientes. Y si quiere soportar formas exponenciales ( "1.3e12" ) se vuelve más complejo.

Para usar esto con un TextField , la forma recomendada es usar un TextFormatter . TextFormatter consta de dos cosas: un convertidor para convertir entre el texto y el valor que representa (un Double en su caso: puede simplemente usar el DoubleStringConverter incorporado), y viceversa, y luego un filtro. El filtro se implementa como una función que toma un objeto TextFormatter.Change y devuelve un objeto del mismo tipo. Normalmente deja el objeto Change tal como está y lo devuelve (para aceptar el Change "as is"), o lo modifica de alguna manera. También es legal devolver null para representar "sin cambios". Entonces, en su caso simple aquí, simplemente examine el nuevo texto propuesto, vea si coincide con la expresión regular, devuelva el cambio "tal cual" si coincide y devuelva null contrario.

Ejemplo:

import java.util.regex.Pattern; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import javafx.util.converter.DoubleStringConverter; public class NumericTextFieldExample extends Application { @Override public void start(Stage primaryStage) { TextField textField = new TextField(); Pattern validDoubleText = Pattern.compile("-?((//d*)|(//d+//.//d*))"); TextFormatter<Double> textFormatter = new TextFormatter<Double>(new DoubleStringConverter(), 0.0, change -> { String newText = change.getControlNewText() ; if (validDoubleText.matcher(newText).matches()) { return change ; } else return null ; }); textField.setTextFormatter(textFormatter); textFormatter.valueProperty().addListener((obs, oldValue, newValue) -> { System.out.println("New double value "+newValue); }); StackPane root = new StackPane(textField); root.setPadding(new Insets(24)); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }


Puede usar la siguiente expresión regular,

"[^//.]*//.{0,1}[^//.]"

O como VGR ha señalado, "Un período no tiene ningún significado especial dentro de los paréntesis de clase de caracteres y 0 o 1 vez se puede representar con un ''?'' (signo de interrogación)." , entonces también puedes usar

"[^.]*//.?[^.]"

No sé por qué, pero su clase parece agregar un * a la expresión regular, por lo que la expresión regular anterior se convertirá en realidad,

"[^//.]*//.{0,1}[^//.]*"

Lo que significa,

  1. Permitirá cualquier personaje excepto a . 0 o más veces (codicioso).
  2. Permitirá a . 0 o 1 veces
  3. Permitirá cualquier personaje excepto a . 0 o más veces (codicioso).

Esto es lo que pareces necesitar. MANIFESTACIÓN


{[0-9]+//.[0-9]+}

para hacer coincidir cualquier número si esto es de hecho lo que estás queriendo hacer