【发布时间】:2019-04-13 20:21:28
【问题描述】:
我想从字符串中删除所有特殊符号,并且字符串中只有单词 我试过了,但它只给出相同的输出
main() {
String s = "Hello, world! i am 'foo'";
print(s.replaceAll(new RegExp('\W+'),''));
}
输出:Hello, world! i am 'foo'
预期:Hello world i am foo
【问题讨论】:
我想从字符串中删除所有特殊符号,并且字符串中只有单词 我试过了,但它只给出相同的输出
main() {
String s = "Hello, world! i am 'foo'";
print(s.replaceAll(new RegExp('\W+'),''));
}
输出:Hello, world! i am 'foo'
预期:Hello world i am foo
【问题讨论】:
The docs for the RegExp class 声明你应该使用 raw 字符串(以r 为前缀的字符串文字,如@987654323@),如果你以这种方式构造正则表达式。这在您使用转义时尤其必要。
此外,您的正则表达式也会捕获空格,因此您需要对其进行修改。您可以改用RegExp(r"[^\s\w]") - 匹配任何不是空格或单词字符的字符
【讨论】:
有两个问题:
'\W' 不是有效的转义序列,要在常规字符串文字中定义反斜杠,您需要使用 \\,或者使用 raw 字符串文字 (r'...')\W 正则表达式模式匹配任何不是单词字符的字符,包括空格,您需要使用带有单词和空格类的否定字符类,[^\w\s]。使用
void main() {
String s = "Hello, world! i am 'foo'";
print(s.replaceAll(new RegExp(r'[^\w\s]+'),''));
}
输出:Hello world i am foo。
完全支持 Unicode 的解决方案
基于What's the correct regex range for javascript's regexes to match all the non word characters in any script? 的帖子,请记住,Unicode 感知正则表达式中的\w 等于[\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}],您可以在 Dart 中使用以下内容:
void main() {
String s = "Hęllo, wórld! i am 'foo'";
String regex = r'[^\p{Alphabetic}\p{Mark}\p{Decimal_Number}\p{Connector_Punctuation}\p{Join_Control}\s]+';
print(s.replaceAll(RegExp(regex, unicode: true),''));
}
// => Hęllo wórld i am foo
【讨论】:
.replaceAll(new RegExp(r'(?:_|[^\w\s])+', '')
我发现这个问题是为了寻找如何从字符串中删除符号。对于其他想要这样做的人:
final myString = 'abc=';
final withoutEquals = myString.replaceAll(RegExp('='), ''); // abc
【讨论】:
.点字符在正则表达式中表示match any single character。因此,在您的示例中,每个字符都被匹配和替换。如果您只想匹配文字 . 点,则需要将其转义为 RegExp('\\.') 或 RegExp(r'\.') 或 RegExp('[.]')。
从字符串中删除字符“,”:
String myString = "s, t, r";
myString = myString.replaceAll(",", ""); // myString is "s t r"
【讨论】:
第一个解决方案
s.replaceAll(RegExp(",|!|'"), ""); // The | operator works as OR
第二个解决方案
s.replaceAll(",", "").replaceAll("!", "").replaceAll("'", "");
【讨论】: