java字符串操作

来源:百度知道 编辑:UC知道 时间:2024/06/21 10:37:10
能否将"ABC.txt"分解成"ABC"和"txt",只取"ABC".

建议使用lastIndexOf不用使用indexOf('.'),因为不能保证每个文件名只有一个.,鉴于这个原因,split就也不要用了。

split
public String[] split(String regex)根据给定正则表达式的匹配拆分此字符串。
该方法的作用就像是使用给定的表达式和限制参数 0 来调用两参数 split 方法。因此,所得数组中不包括结尾空字符串。

例如,字符串 "boo:and:foo" 使用这些表达式可生成以下结果:

Regex 结果
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }

参数:
regex - 定界正则表达式
返回:
字符串数组,它是根据给定正则表达式的匹配拆分此字符串确定的
抛出:
PatternSyntaxException - 如果正则表达式的语法无效

String str = "ABC.txt";
String[] temps = str.split(".");
temps组就是那两个字符串了,注意别把点号打成正文的啊,要不就挂了。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("(ABC).*");
String s = "ABC.txt";
Matcher m = p.matcher(s);
while(m.find()) {