skip to Main Content

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:

  • abfed124
  • sfaasf(space)1221
  • afasf(space).124,(space)aaf
  • 1242dsdd(space)sddl,.!
  • 1242dsdd(space)sddl,,…!!!!

Non-Acceptable strings:

  • (space)(space)asfa
  • (space)asf112
  • @ajsfas
  • aas(space)(space)(space),asa(space)(space)(space)as

2

Answers


  1. try this regex

    RegExp regex = RegExp(r'^(?!.*ss)[w,.! ]+$');
    
    Login or Signup to reply.
  2. Try this code

    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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search