我一直在尝试找出可以过滤不是'-'或0-9的字符的REGEX表达式。该表达式将与文档过滤器一起使用,该过滤器将过滤插入JTextFields中的字符。让我更详细地说明...
当用户在JTextField中输入字符时,DocumentFilter使用DocumentFilter类中的'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
}
}
如果您认为我朝错误的方向前进,请告诉我。我愿意接受一个更简单的选择。
答案 0 :(得分:0)
发布此问题后,我终于弄清楚了! (有趣的结果如何)
正则表达式:^(-{1})|(-[1-9])|(-[1-9]([0-9]{1,}))|([0-9]{1,})$
对于任何不认识(如我)的人||是正则表达式中的OR符号。因此,该表达式将允许通过逐步匹配字符串来传递值,
(-{1})
传递一个'-'
(-[1-9])
传递一个'-',后面附加一个非零整数
(-[1-9]([0-9]{1,}))
传递一个'-',后面附加一个非零整数,并且在此传递之后还允许任意数量的整数
([0-9]{1,})
传递任何正整数,而不考虑起始整数
希望这会有所帮助!
答案 1 :(得分:0)
代替所有替代,将其归因于此
"^(?=[-\\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中所有剩余的无效尾随字符。
所有这一切都需要测试是否存在匹配项。
当然,您需要匹配器来获取组。
可能的结果:
"^(?=.)((?:-(?>(?=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+$"