gpt4 book ai didi

regex - 无法识别Dart RegExp空白

转载 作者:行者123 更新时间:2023-12-03 03:20:33 25 4
gpt4 key购买 nike

我正在尝试为用户名实现一个正则表达式模式,该模式允许英文字母,阿拉伯字母,数字,破折号和空格。
即使输入\ s包含在模式中,以下模式也始终不返回匹配项

Pattern _usernamePattern = r'^[a-zA-Z0-9\u0621-\u064A\-\s]{3,30}$';
我也尝试用“”和\\ s替换\ s,但是对于任何有空格的输入,正则表达式始终不返回任何匹配项。
编辑:事实证明,当使用带有LTR或RTL混合语言的文本字段时,flutter会为“从右到左标记”或“从左到右标记”添加一个Unicode字符。这个额外的标记是一个Unicode字符,已添加到文本中。由于此附加字符,上述正则表达式失败。要解决此问题,只需对这些字符执行replaceAll即可。在此处阅读更多信息: https://github.com/flutter/flutter/issues/56514

最佳答案

这是一个非常棘手的问题,值得在此处给出答案。
source中所述:

  /// When LTR text is entered into an RTL field, or RTL text is entered into an
/// LTR field, [LRM](https://en.wikipedia.org/wiki/Left-to-right_mark) or
/// [RLM](https://en.wikipedia.org/wiki/Right-to-left_mark) characters will be
/// inserted alongside whitespace characters, respectively. This is to
/// eliminate ambiguous directionality in whitespace and ensure proper caret
/// placement. These characters will affect the length of the string and may
/// need to be parsed out when doing things like string comparison with other
/// text.
虽然这是很好的做法,但在使用混合的LTR / RTL文本模式时(如此处所示),可能会导致问题,并且必须确保确切的字段长度等。
suggested解决方案是删除所有 left-right-marks:
void main() {
final String lrm = 'aaaa \u{200e}bbbb';
print('lrm: "$lrm" with length ${lrm.length}');

final String lrmFree = lrm.replaceAll(RegExp(r'\u{200e}', unicode: true), '');
print('lrmFree: "$lrmFree" with length ${lrmFree.length}');
}
相关: right-to-left (RTL) in flutter

关于regex - 无法识别Dart RegExp空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63491477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com