我有一个字符串,因为String placeStr="place1*place2*place3"
我想让数组包含place1,place2,place3如下:
String[] places=placeStr.split("*");
System.out.println(places[0]);
Run Code Online (Sandbox Code Playgroud)
但它显示错误E/AndroidRuntime(32118):引起:java.util.regex.PatternSyntaxException:索引1附近的regexp模式中的语法错误:*
我认为原因是字符"*".如果我改变* - ,它显示确定.我该怎么办?
使用Regexp时,\*表示0 or more最后定义的表达式的实例.所以举个例子.
s*意味着匹配任何具有0或更多"s"的东西.这将匹配"ss","sssss"或"".
当我们想要实际搜索*,而不是将其用作运算符时,我们需要escape使用该\字符.但是,单数\用于特殊字符(例如\s和\t),因此我们还需要使用另一个字符来转义该字符\.
这导致:
\ (ignore the next slash)
\ (ignore the star)
* (would be 0 or many, but its been ignored so means the literal.)
Run Code Online (Sandbox Code Playgroud)
或者换句话说
\\*
Run Code Online (Sandbox Code Playgroud)
在Java中,我们可以像这样使用它:
String[] places=placeStr.split("\\*");
System.out.println(places[0]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
780 次 |
| 最近记录: |