regexflutterdartregular-language

How can I allow a single space in a regex in Dart but allow other characters to be 1 or more?


I've looked through tons of stuff and all point to just add a space in the regex but it doesn't work for me, can you explain why and how can I make it work?

Right now the expression I am using is this and its written in javascript which means it allows the user to use \s for space but in dart its just a single space " ".

RegExp(r'''^[\w\'\’\"_,.()&!*|:/\\–%-]+(?:\s[\w\'\’\"_,.()&!*|:/\\–%-]+)*?\s?$''');

I am trying to accept only alpha-numeric characters at start of the string and then after a character or word it should only allow a single space but other characters can be more than that.

This is how I am using it in my code.

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;
  }

For example,

Accepted strings:

Non-Acceptable strings:


Solution

  • try this regex

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