escape " regexp in dart

谁说胖子不能爱 提交于 2021-02-10 08:24:12

问题


I'm trying to catch symbols in a dart Regexp. My regexp looks like this:

  RegExp containsSymbolRegExp = RegExp(r"[-!$%^&*()_+|~=`{}\[\]:;'<>?,.\/]");

However, I also need to make it catch the symbol " I can't stick " in there though, since it messes with the string. Any ideas how to do this? Thanks.

edit: jamesdlin's answer works great for dart. But it doesn't work for my flutter app, so I'm thinking it has something to do with flutter. Here's the code I'm applying this to:

TextEditingController _passwordController = TextEditingController();
bool containsSymbol;

RegExp containsSymbolRegExp = RegExp(r"[-!$%^&*()_+|~=`{}#@\[\]:;'<>?,.\/"
      '"'
      "]");

void _handleChange(text) {
    setState(() {
        containsSymbol = containsSymbolRegExp.hasMatch(_passwordController.text);
    });
    print(containsSymbol); // always prints false for " ' \ but works for all other symbols
  }

Widget _textField(controller, labelText) {
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Text(labelText, style: TextStyle(fontSize: 11)),
      Container(
        width: MediaQuery.of(context).size.width * 0.9,
        height: 35,
        child: TextField(
          onChanged: _handleChange,
          style: TextStyle(fontSize: 20),
          keyboardType: TextInputType.text,
          controller: _passwordController,
          cursorColor: Colors.grey,
          decoration: InputDecoration(
              focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.grey))),
        ),
      ),
    ],
  );
}

回答1:


You could take advantage of string concatenation of adjacent string literals and either use a single-quoted string or use a non-raw string with " escaped:

RegExp(
  r"[-!$%^&*()_+|~=`{}\[\]:;'<>?,.\/"
  '"'
  "]");

Alternatively you always could use a non-raw string with more escapes:

RegExp(
  "[-!\$%^&*()_+|~=`{}\\[\\]:;'<>?,.\\/\"]");

although that's messier.




回答2:


To answer to the edited part of your question being that it worked in Dart but not in Flutter...

It is because apostrophes/quotation marks from TextField values in Flutter are right quotation marks and therefore come in different Unicode.


For apostrophes, it's U+2019 () instead of U+0027 (')

For quotation marks, U+201D () instead of U+0022 (")


The Regex you were trying with is not capturing for such characters. Therefore, you just need to add those into your Regex.

RegExp containsSymbolRegExp = RegExp(
   r"[-!$%^&*()_+|~=`{}#@\[\]:;'’<>?,.\/"
   '"”'
   "]");

Tip: Debug! :) I can already see some part of the value looking funny the moment it hits the breakpoint of where the value was about to be evaluated.



来源:https://stackoverflow.com/questions/58141263/escape-regexp-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!