如何使JTextField或JFormattedTextField只有在匹配REGEX模式时才接受输入? [英] How to make JTextField or JFormattedTextField accept input only if it matches a REGEX pattern?

查看:151
本文介绍了如何使JTextField或JFormattedTextField只有在匹配REGEX模式时才接受输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我想要一些 JTextField ,只接受新的输入,如果它匹配特定的 Pattern / p>

我知道关于 JFormattedTextField 的掩码,那就是而不是

对于每个新的输入,如果符合特定正则表达式模式的流程,文本应该只接受更改。



这必须用正则表达式来完成,因为正则表达式要求的情况,比如输入应该接收自身的一部分。例如:

假设我的正则表达式是(\\ d {2}) - bk\\ d {3} \\.\\1\"
输入123-bk001。时,下一个输入的字符必须与第一个组相同,这意味着只有输入3个字符才能被接受它们分别等于 123
输入456-bk404。将要求下一个字符是456



我该怎么做?






编辑:



说明没有正则表达式就难以解决的情况之一,我的实际用途不会局限于此。所以,如果可能的话,答案应该是更广泛的可用性(作为问题的标题),而不是具体到这个例子。

如果这是不可能的,或者比为几个(3-5个)不同情况实施特定解决方案更困难,请随时告诉。

div>

  • 使用 DocumentFilter 用于删除或替换已定义的不需要的字符(也许可以使用 NavigationFilter.Bias


  • 您可以定义自己的 / =nofollow noreferrer> InputMask with InputVerifier



I want a few JTextField within my program to only accept new input if it matches an specific Pattern.

I know about JFormattedTextField's masks and that is not what I want here.

For each new input, the text should only accept the changes if those comply with the flow of an specific regex pattern.

This has to be done with regex because of "regex-demanding" situations, like if the input should receive parts of itself. This is better understood with an example:

Suppose my regex is "(\\d{2})-bk\\d{3}\\.\\1". With an input of "123-bk001.", the next inputted characters must be equal to the first group, meaning the 3 inputted characters should only be accepted if they equal 123, respectively. An input of "456-bk404." would require the next chars to be "456" instead.

How can I do it?


Edit:

This example is just to illustrate one of the situations that is hard to solve without regex, and my actual uses would not be limited to it. So, if possible, answers should be of the broader usability (as of the question's tittle), rather than specific to this example.

But if it's not possible or if it would be harder than implementing specific solutions for the few (3-5) different cases, feel free to tell.

解决方案

这篇关于如何使JTextField或JFormattedTextField只有在匹配REGEX模式时才接受输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆