1
/**
2
* 從指定的字符串中提取Email
3
* content 指定的字符串
4
*/
5
public static String parse(String content) {
6
String email = null;
7
if (content==null || content.length()<1) {
8
return email;
9
}
10
//找出含有@
11
int beginPos;
12
int i;
13
String token = "@";
14
String preHalf="";
15
String sufHalf = "";
16
17
beginPos = content.indexOf(token);
18
if (beginPos>-1) {
19
//前項掃描
20
String s = null;
21
i= beginPos;
22
while(i>0) {
23
s = content.substring(i-1,i);
24
if (isLetter(s))
25
preHalf = s+preHalf;
26
else
27
break;
28
i--;
29
}
30
//后項掃描
31
i= beginPos+1;
32
while( i<content.length()) {
33
s = content.substring(i,i+1);
34
if (isLetter(s))
35
sufHalf = sufHalf +s;
36
else
37
break;
38
i++;
39
}
40
//判斷合法性
41
email = preHalf + "@" + sufHalf;
42
if (isEmail(email)) {
43
return email;
44
}
45
}
46
return null;
47
}
48
49
/**
50
* 判斷是不是合法Email
51
* email Email地址
52
*/
53
public static boolean isEmail(String email) {
54
try {
55
if (email==null || email.length()<1 || email.length()>256) {
56
return false;
57
}
58
59
String check = "^([0-9a-zA-Z]+[_.0-9a-zA-Z-]+)@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2,3})$";
60
Pattern regex = Pattern.compile(check);
61
Matcher matcher = regex.matcher(email);
62
boolean isMatched = matcher.matches();
63
if(isMatched) {
64
return true;
65
} else {
66
return false;
67
}
68
} catch (RuntimeException e) {
69
return false;
70
}
71
}
72
73
/**
74
* 判斷是不是合法字符
75
* c 要判斷的字符
76
*/
77
public static boolean isLetter(String c) {
78
boolean result = false;
79
80
if (c==null || c.length()<0) {
81
return false;
82
}
83
//a-z
84
if (c.compareToIgnoreCase("a")>=0 && c.compareToIgnoreCase("z")<=0) {
85
return true;
86
}
87
//0-9
88
if (c.compareToIgnoreCase("0")>=0 && c.compareToIgnoreCase("9")<=0) {
89
return true;
90
}
91
//. - _
92
if (c.equals(".") || c.equals("-") || c.equals("_") ) {
93
return true;
94
}
95
return result;
96
}
97

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97
