表达式含义:formula.split(“[\\ *]”)和obj1.replaceAll(“\\。”,“”);

时间:2016-05-25 14:51:41

标签: java regex

请问,这些代码行的含义是什么?

// What is meant by formula.split ("[\\ *]"); ???

 String[] temp = formula.split("[\\*]");

//Indicate what they want and why these substitutions twice on the same subject ??? Does this have a specific meaning ???

obj1 = obj1.replaceAll ("\\.", "");
obj1 = obj1.replaceAll (",", ".");

感谢那些会给我解释的人

3 个答案:

答案 0 :(得分:0)

split()replaceAll()和正则表达式

split()函数实际上接受regular expression patterns来处理拆分操作,而不是使用您可能期望的普通字符串。

// This would take your string and split it on an explicit '*' character
String[] temp = formula.split("[\\*]");

模式[\\*]是一个与显式星号*匹配的字符集,因为\\通常用作转义字符。因此,当遇到一次时,它将被添加到输出数组中:

// Example use-case
String[] temp = "a\b*c".split("[\\*]"); // yields ["a\b","c"]

同样,replaceAll()函数也接受正则表达式来处理替换。

// This would replace any periods with commas (escaping is required as '.' matches all) 
obj1 = obj1.replaceAll ("\\.", "");
// This would replace and commas with periods (no escaping required as ',' isn't special)
obj1 = obj1.replaceAll (",", ".");

由于这两个操作分别做了两件事,你实际上无法将它们组合起来(第一个是替换斜杠后面的字符,另一个是用句点替换逗号)。

答案 1 :(得分:0)

首先会在字符串中找到ever *。 "foo*bar*war*boo".split("[\\*]"); => [foo, bar, war, boo]

秒将删除所有.

第三个会将所有,更改为.

答案 2 :(得分:0)

String[] temp = formula.split("[\\*]");

当符合*符号时,它会将字符串拆分为多个部分。 "[\\*]"是一个正则表达式,它告诉我们在哪里拆分字符串。使用\\,因为*是正则表达式中的特殊字符。

obj1 = obj1.replaceAll ("\\.", "");

此行会删除.中的所有obj1

obj1 = obj1.replaceAll (",", ".");

这一行用,替换obj1中的每个.

以下是一些例子:

String s = "it*is*string";
String[] tmp = s.split("[\\*]");
System.out.println(Arrays.toString(tmp));
String s1 = "remove .dots.,please,.";
s1 = s1.replaceAll("\\.", "");
s1 = s1.replaceAll (",", ".");
System.out.println(s1);

输出:

[it, is, string]
remove dots.please.