Java 带有文档过滤器的正则表达式

Java REGEX With Document Filter

我一直在尝试找出一个可以过滤不是'-'或0-9的字符的REGEX表达式。此表达式将与文档过滤器一起使用,该过滤器将过滤插入到 JTextFields 中的字符。让我更详细地解释...

当用户在 JTextField 中输入字符时,DocumentFilter 使用 DocumentFilter class 中的 replace 方法检查输入。因为每次插入字符时都会调用该方法,所以 REGEX 需要能够在用户构建字符串时处理整数的一部分。例如,

Key Press 1): Value = '-' PASS
Key Press 2): Value = '-1' PASS
Key Press 3): Value = '-10' PASS etc...

但是过滤器不应允许“-0”或“--”组合,并且应通过以下情况,

仅限负号 ('-')

“-”旁边没有零的负数(“-01”失败)

正值(0122 和 122 通过)

这是我的代码:

package regex;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class CustomFilter extends DocumentFilter {

    private String regex = "((-?)([1-9]??))(\d)";

    /**
     * Called every time a new character is added.
     */
    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {

        String text = fb.getDocument().getText(0, fb.getDocument().getLength());
        text += string;

        if(text.matches(regex)) {
            super.insertString(fb, offset, string, attr);
        }
    }

    /**
     * Called when the user pastes in new text.
     */
    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {

        String string = fb.getDocument().getText(0, fb.getDocument().getLength());
        string += text;

        if(string.matches(regex)) {
            super.replace(fb, offset, length, text, attrs);
        }
    }

    @Override
    public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
        super.remove(fb, offset, length); // I may modify this later
    }
}

如果您认为我的方向有误,请告诉我。我愿意接受更简单的选择。

发完这个问题我终于想通了! (有趣的事情是如何解决的)

正则表达式:^(-{1})|(-[1-9])|(-[1-9]([0-9]{1,}))|([0-9]{1,})$

对于不知道的人(比如我),| 是正则表达式中的 OR 符号。所以这个表达式将允许值通过在步骤中匹配字符串来传递,

(-{1}) 传递一个'-'

(-[1-9]) 传递一个 '-' 附加一个非零整数

(-[1-9]([0-9]{1,})) 传递附加一个非零整数的“-”,并且在此传递后还允许任意数量的整数

([0-9]{1,}) 传递任何正整数而不考虑起始整数

希望对您有所帮助!

而不是所有的交替,把它分解成这个

"^(?=[-\d])(?:-(?!0))?\d*$"

已解释

 ^                             # Beginning of string
 (?= [-\d] )                   # Must be a character in it
 (?:                           # Optional minus sign
      -
      (?! 0 )                       # If not followed by 0
 )?
 \d*                           # Optional digits [0-9]
 $                             # End of string

Mod:

稍加努力,您可以获得
中的部分有效字符串 捕获第 1 组和第 2 组中任何剩余的 无效尾随字符

所有这一切都需要测试是否存在匹配项。
当然你需要匹配器来获取组。

可能的结果:

  1. 正则表达式不匹配,字符串为空。
    行动:不采取任何行动。
  2. 正则表达式匹配。
    一个。操作:如果第 2 组的长度 > 0,写入文本字段
    使用第 1 组字符串,并将光标放在末尾。
    b。操作:如果组 2 的长度 == 0,则不采取任何操作,输入正确。

"^(?=.)((?:-(?>(?=0)|\d*)|\d*))(.*)$"

https://regex101.com/r/oxmZfa/1

已解释

 ^                             # Beginning of string

 (?= . )                       # Must be a character in the string

 (                             # (1 start), Template for pattial validity
      (?:
           -                             # The case for minus
           (?>                           # Atomic group for safety
                (?= 0 )                       # Don't capture 0 if it's ahead
             |                              # or,
                \d*                           # Any digits, 0 won't be first
           )
        |                              # or, the case for No minus
           \d*                           # Any digits
      )
 )                             # (1 end)

 ( .* )                        # (2), This is to be trimmed, stuff here doesn't match the template

 $                             # End of string

当用户提交文本时使用此正则表达式来验证输入。
如果不匹配,说明用户没有在字段中添加数字。
只是弹出输入不完整的消息。

"^(?=[-\d])(?:-(?!0))?\d+$"