简体   繁体   English

正则表达式 Java 由星号分割的字符串

[英]Regex Java String Split by Asterisk

Help is needed.需要帮助。

line.split("*");

I used this line of code to split a string into an asterisk mark.我使用这行代码将一个字符串拆分为一个星号标记。 However, I got an error from my compiler.但是,我的编译器出错了。 It says, "INVALID REGULAR EXPRESSION: DANGLING META CHARACTER '*'"它说,“无效的正则表达式:悬挂元字符'*'”

How to resolve this problem?如何解决这个问题? Thanks in advance.提前致谢。

* has special meaning in regular expressions. *在正则表达式中具有特殊意义。 You have to escape it.你必须逃避它。

line.split("\\*");

试试这个语句:

line.split("\\*");

It is because you used a "*", that is a regular expression.这是因为您使用了“*”,即正则表达式。 If you want to use this caracter, you need tu put something like that:如果你想使用这个角色,你需要输入这样的东西:

line.split("\\*");

* is a meta character in regular expression. *是正则表达式中的元字符。 It is used for matching 0 or more elements.它用于匹配 0 个或多个元素。 If you want to use * as a normal character and not as a special character (ie skip its behavior as a meta character) then add escape characters before it.如果您想将*用作普通字符而不是特殊字符(即跳过其作为元字符的行为),则在它之前添加转义字符。

Eg: String[] split = line.split("\\\\*");例如: String[] split = line.split("\\\\*");

Hope this helps.希望这可以帮助。

As shown in the following table , * has a special meaning, zero or more times .如下所示, *有特殊含义,零次或多次

Greedy贪婪的 Reluctant不情愿的 Possessive所有格 Meaning意义
X? X? X?? X?? X?+ X?+ X, once or not at all X,一次或一次都没有
X* X* X*? X*? X*+ X*+ X, zero or more times X,零次或多次
X+ X+ X+? X+? X++ X++ X, one or more times X,一次或多次
X{n} X{n} X{n}? X{n}? X{n}+ X{n}+ X, exactly n times X,恰好 n 次
X{n,} X{n,} X{n,}? X{n,}? X{n,}+ X{n,}+ X, at least n times X,至少n次
X{n,m} X{n,m} X{n,m}? X{n,m}? X{n,m}+ X{n,m}+ X, at least n but not more than m times X,至少n次但不超过m次

Therefore, you need to escape it with a \ .因此,您需要使用\对其进行转义。 However, \ too is a special character and therefore you need to put an additional \ to escape \ .但是, \也是一个特殊字符,因此您需要添加一个额外的\来转义\ Thus, the required pattern becomes \\* .因此,所需的模式变为\\*

String[] arr = line.split("\\*");
System.out.println(java.util.Arrays.toString(arr));

Use this用这个

" String data= "Mani*Kum"; " String data="玛尼*库姆";

String []value= data.split("\\*");

" The output will like this: " 输出将是这样的:

value[0]= "Mani";
value[1]= "Kum";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM