我已经查看了大量的内容,所有内容都指向在正则表达式中添加一个空格,但它对我不起作用,你能解释一下为什么以及如何让它起作用吗?
现在我使用的表达式是这个,它是用 javascript 编写的,这意味着它允许用户使用 \s 来表示空格,但在 dart 中它只是一个空格“”。
RegExp(r'''^[\w\'\’\"_,.()&!*|:/\\–%-]+(?:\s[\w\'\’\"_,.()&!*|:/\\–%-]+)*?\s?$''');
我试图在字符串开头仅接受字母数字字符,然后在字符或单词之后应该只允许一个空格,但其他字符可以多于这个。
这就是我在代码中使用它的方式。
inputFormatters: [
RegexInputFormatter(featureRegex),
],
class RegexInputFormatter extends TextInputFormatter {
final RegExp regex;
RegexInputFormatter(this.regex);
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final String newText = newValue.text;
final String filteredText = _getFilteredText(newText);
if (newText != filteredText) {
final int selectionIndex = newValue.selection.end - (newText.length - filteredText.length);
return TextEditingValue(
text: filteredText,
selection: TextSelection.collapsed(offset: selectionIndex),
);
}
return newValue;
}
例如,
接受的字符串:
不可接受的字符串:
尝试这个正则表达式
RegExp regex = RegExp(r'^(?!.*\s\s)[\w,.! ]+$');