0

I want to allow any letters or digits and if used, allow # only at the beginning with only one occurence something like #{1}. And keep those restrictions that I already have in the expression for characters ^<>@.\/().

Here is my Regex:

/^[#?a-zA-z0-9][^<>@.\/()]+/g

Some use cases I want this regex expression to pass:

##msidfipds - fail (2 of #)
fdsfsdfd#1m - fail (# not 1st character)
vcvxcvxcvxc - pass
#fdfdsfsdfs - pass

Use case for TextField widget.

TextField(
    inputFormatters: <TextInputFormatter>[
           FilteringTextInputFormatter.allow(RegExp(r'^#?[a-zA-Z0-9][^#<>@.\/()]*$')),
   ],
   autofocus: true,
   enableInteractiveSelection: true,
   keyboardType: TextInputType.text,
   decoration: InputDecoration(
       fillColor: Colors.transparent,
       border: InputBorder.none,
       hintText: 'Search',
   ),
   textAlign: TextAlign.center,
   style: TextFieldStyle,
),
user12051965
  • 97
  • 9
  • 29

2 Answers2

1

Use a beginning anchor, and then an optional quantifier:

/^#?[a-zA-Z0-9][^<>@.\/()]+/g

This will ensure that if an octothorpe occurs, it must occur at the beginning of the string.

zr0gravity7
  • 2,917
  • 1
  • 12
  • 33
1

You can use

^#?[a-zA-Z0-9][^#<>@.\/()]+$

See the regex demo.

NOTE: [A-z] matches more than just letters, you need [A-Za-z] to only match letters.

Details:

  • ^ - start of string
  • #? - an optional # char
  • [a-zA-Z0-9] - an alphanumeric char
  • [^#<>@.\/()]+ - one or more chars other than #, <, >, @, ., /, ( and )
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Hey @Wiktor, thank you for your answer but I have not yet been able to find a solution. I needed that Regex in order to restrict user input. I have found the following asnwer to question that I want to use for my TextField.: https://stackoverflow.com/questions/56390839/flutter-regex-in-textformfield I have updated my question, and right now my TextField is blocked and cannot type anything there. – user12051965 Jul 27 '21 at 22:08
  • @user12051965 Maybe because even one single char input should be matched with the regex. Try `^#?[a-zA-Z0-9][^#<>@.\/()]*$` – Wiktor Stribiżew Jul 27 '21 at 22:10
  • I tried exactly this and cannot type '#' at the beginning, only letters and digits, and when I write # somewhere in the middle it deletes everything in input. – user12051965 Jul 27 '21 at 22:35