您的位置:首页 > 编程语言 > Java开发

Thinking in Java:第十三章-字符串与正则表达式

2017-12-30 11:51 519 查看
1:String的定义:public final class String implements java.io.Serializable, Comparable<String>, CharSequence
2:String 对象不可变的,String 类中每一个看起来会修改String值的方法,实际上都是创建了一个全新的Sring 对象,以包含修改后的字符串内容,而最初的String对象不变。
3:String 字符串的拼接底层是用StringBuilder实现的,但是在复杂的字符串拼接中我们最好还是是用StringBulider,然后再调用toString()方法。
4:java se5引入的format方法可用于PrintStream或者PrintWriter对象,其中也包括System.out对象。format方法模仿自C。
SimpleFormat
public class SimpleFormat {

public static void main(String[] args) {
int a = 5;

double b = 3.567;

System.out.println("row 1: " + "[" + a + " " + b +"]");

System.out.format("row 2: [%d %f]\n", a, b);

System.out.printf("row 3: [%d %f]\n", a, b);
}
}


5:Formatter类
当你创建一个Formatter对象时,需要向其构造器传递一些信息,告诉它最终结果向哪里输出
Turtle
/**
* Created by ivalue on 2017/12/29.
*/
public class Turtle {

private String name;

private Formatter f;

public Turtle(String name, Formatter f) {
this.name = name;
this.f = f;
}

public void show(int x, int y) {
f.format("%s the turtle is at (%d,%d)\n", name, x, y);
}

public static void main(String[] args) {
PrintStream outAlias = System.out;

Turtle t1 = new Turtle("Tommy", new Formatter(outAlias));

t1.show(3,4);
t1.show(4,6);
}
}


正则表达式
1:再其他语言中,\\表示“我想要在正则表达式中插入一个普通的反斜杠,请不要给它特殊含义。” 而在java中,\\的意思是“我想要插入一个正则表达式的反斜杠,所以其后的字符串具有特殊工艺的意义”。例如表达一位数字,正则表达式应该是\\d, 如果向插入一个普通的反斜杠,则应该这样\\\\。
SimpleMatch
public class SimpleMatch {

public static void main(String[] args) {
// + 需要\\+
System.out.println("1234".matches("(-|\\+)?\\d+"));

System.out.println("\\".matches("\\\\"));
}
}


2:String 类还自带一个正则表达式工具--spilt()方法,其功能是“将字符串从正则表达式匹配的地方切开”。
Splitting
public class Splitting {

public static String knights = "Then, when you hava found shrubbery, you" +
"must cut down the mightiest tree";

public static void split(String regex) {
System.out.println(Arrays.toString(knights.split(regex)));
}

public static void main(String[] args) {
split(" ");
split("\\W+");
split("n\\W+");
}
}


3:正则表达式中的Pattern, Matcher类
3.1:Matcher.find()方法可以用来在Charsequence中查找多个匹配
SimpleRegular
public class SimpleRegular {

public static void main(String[] args) {
String str = "Java now has regular expressions";

//        Pattern pattern = Pattern.compile("^Java");

// {0,3}那就是不管怎样都能匹配了
//        Pattern pattern = Pattern.compile("s{1,3}");

/*
* 模式\\w+,将字符串分为字符,find()像迭代器那样前向遍历输入字符串,第二个find()能够
* 接受一个整数作为参数,该整数表示字符串中字符的位置,并以其作为搜索的起点,后一个版本
* 的find()方法能根据其参数的值,不断重新设定搜索的起点位置。
* */
Pattern pattern = Pattern.compile("\\w+");

Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
System.out.println("match " + matcher.group() + " at position: " + matcher.start()
+ "-" + (matcher.end()-1));
}

int i = 0;
while (matcher.find(i)) {
System.out.println("match " + matcher.group() + " at position: " + matcher.start()
+ "-" + (matcher.end()-1));
i++;
}
}
}


3.2:组(Groups)
public String group(), 返回前一次操作的第0组(整个匹配)
public int start(), 返回在前一次匹配操作中寻找到的组的起始索引
public int end(), 返回在前一次匹配操作中寻找到的组的最后一个字符索引加1的值
注意:find()可以在输入的任意位置定位正则表达式,而lookingat()和matcher()只有在正则表达式与输入的最开始除就开始匹配才会成功。matches()只有在整个输入都匹配正则表达式才会成功,而lookingAt()只要输入的第一部分匹配就会成功。
Flm
/**
* boolean matches()
* boolean lookingAt()
* boolean find()
* boolean find(int start)
* Pattern.CASE_INSENSITIVE 忽略大小写
*/
public class Flm {

public static void main(String[] args) {
Pattern p = Pattern.compile("Java", Pattern.CASE_INSENSITIVE);

Matcher m = p.matcher("is java very popular");

System.out.println(m.find());
System.out.println(m.lookingAt());
System.out.println(m.matches());
}
}


3.3:替换操作
replaceFirst(String replacement)替换第一个匹配成功的部分
replaceAll(String replacement)
TheRepla
4000
cement
public class TheReplacement {

public static String input = "Here's  a block of text to use as input to" +
"the regular expression matcher.Note  that we'll first" +
"use it.";

public static void main(String[] args) {

String s = "";

Matcher m = Pattern.compile(".*", Pattern.DOTALL).matcher(input);

if (m.find()) {
s = m.group();
}

s = s.replaceAll(" {2,}", " ");
System.out.println(s);
}
}


3.4:reset()方法,可以将现有的Matcher对象应用于一个新的字符序列

3.5:使用正则表达式扫描
ThreatAnalyzer
public class ThreatAnalyzer {

static String threadData =
"58.27.86.161@02/10/2017\n" +
"34.55.86.161@03/15/2017\n" +
"33.45.86.161@03/15/2017\n" +
"[next log section with different data format]";

public static void main(String[] args) {
Scanner sc = new Scanner(threadData);
String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@(\\d{2}/\\d{2}/\\d{4})";
while (sc.hasNext(pattern)) {
sc.next(pattern);
MatchResult matchResult = sc.match();
String ip = matchResult.group(1);
String date = matchResult.group(2);
System.out.println("Thread from " + ip + " on " + date);
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息