如何在Dart中允许正则表达式中的单个空格,但允许其他字符为1或更多?

zlwx9yxi  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(70)

我看了很多东西,所有的东西都指向在正则表达式中添加一个空格,但它对我不起作用,你能解释一下为什么吗?我怎么才能让它起作用呢?
现在我使用的表达式是this,它是用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;
  }

比如说,
接受的字符串:

  • 亚洲人124
  • sfaasf(space)1221
  • afasf(空格).124,(空格)aaf
  • 1242dsdd(space)sddl,.!
  • 1242dsdd(space)sddl,,...!!!!

不可接受的字符串:

  • (space)(space)asfa
  • (space)
  • 联系我们
  • aas(空间),阿萨(空间)作为
f45qwnt8

f45qwnt81#

试试这个正则表达式

RegExp regex = RegExp(r'^(?!.*\s\s)[\w,.! ]+$');
tktrz96b

tktrz96b2#

试试这个代码

void main() {
  RegExp r = RegExp(r'^[^\s]*(?:\s[^\s]*)?$');

  String input1 = "HelloWorld";      // Valid
  String input2 = "Hello World";     // Valid
  String input3 = "Hello!123";       // Valid
  String input4 = "SpecialChars@#";  // Valid
  String input5 = "Too  Many Spaces"; // Invalid due to two spaces

  print(r.hasMatch(input1)); // true
  print(r.hasMatch(input2)); // true
  print(r.hasMatch(input3)); // true
  print(r.hasMatch(input4)); // true
  print(r.hasMatch(input5)); // false
}

相关问题