-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.go
executable file
·516 lines (472 loc) · 11.6 KB
/
string.go
1
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
package golibs
import (
"bytes"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
math_rand "math/rand"
"net"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
)
//使用 utf8.RuneCountInString()统计字符串长度
func Length(str string) int {
return utf8.RuneCountInString(str)
}
//字串截取
func SubString(s string, pos, length int) string {
runes := []rune(s)
l := pos + length
if l > len(runes) {
l = len(runes)
}
return string(runes[pos:l])
}
//字符串逆序
func ReverseString(s string) string {
str := []rune(s)
for i, j := 0, len(str)-1; i < j; i, j = i+1, j-1 {
str[i], str[j] = str[j], str[i]
}
return string(str)
}
//获取文件扩展名
func GetFileSuffix(s string) string {
re, _ := regexp.Compile(".(jpg|jpeg|png|gif|exe|doc|docx|ppt|pptx|xls|xlsx)")
suffix := re.ReplaceAllString(s, "")
return suffix
}
//生成指定范围内的int64数字
func RandInt64(min, max int64) int64 {
max_bigint := big.NewInt(max)
i, _ := rand.Int(rand.Reader, max_bigint)
if i.Int64() < min {
RandInt64(min, max)
}
return i.Int64()
}
//删除空格、换行、空格等字符
func Strim(s string) string {
s = strings.Replace(s, "\t", "", -1)
s = strings.Replace(s, " ", "", -1)
s = strings.Replace(s, "\n", "", -1)
s = strings.Replace(s, "\r", "", -1)
return s
}
//字符串转成Unicode编码
func String2Unicode(s string) string {
json := ""
for _, r := range s {
rint := int(r)
if rint < 128 {
json += string(r)
} else {
json += "\\u" + strconv.FormatInt(int64(rint), 16)
}
}
return json
}
//Unicode编码转成字符串
func Unicode2String(s string) (to string, err error) {
bs, err := hex.DecodeString(strings.Replace(s, `\u`, ``, -1))
if err != nil {
return
}
for i, bl, br, r := 0, len(bs), bytes.NewReader(bs), uint16(0); i < bl; i += 2 {
binary.Read(br, binary.BigEndian, &r)
to += string(r)
}
return
}
//html编码
func HTMLEncode(s string) string {
html := ""
for _, r := range s {
html += "&#" + strconv.Itoa(int(r)) + ";"
}
return html
}
//获取一个Guid
func GetGuid() string {
b := make([]byte, 48)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return Md5(Base64(b))
}
//把IP地址转成数字
func GetIPNums(s string) (ipNum uint32, err error) {
if strings.EqualFold(s, "") {
return ipNum, errors.New("ipAddress is null")
}
items := strings.Split(s, ".")
if len(items) != 4 {
return ipNum, errors.New("ipAddress is error")
}
item0, err := strconv.Atoi(items[0])
if err != nil {
return ipNum, errors.New("ipAddress is error0")
}
item1, err := strconv.Atoi(items[1])
if err != nil {
return ipNum, errors.New("ipAddress is error1")
}
item2, err := strconv.Atoi(items[2])
if err != nil {
return ipNum, errors.New("ipAddress is error2")
}
item3, err := strconv.Atoi(items[3])
if err != nil {
return ipNum, errors.New("ipAddress is error3")
}
return uint32(item0<<24 | item1<<16 | item2<<8 | item3), nil
}
//获取IP地址,不包含端口号
func GetIPAddressNotPort(ip_address string) string {
if !strings.Contains(ip_address, ":") {
return ip_address
}
start := strings.Index(ip_address, ":")
if start <= 2 {
return ip_address
}
return SubString(ip_address, 0, start)
}
//判断是否是淘宝用户名
func IsTaobaoNick(s string) bool {
if len(s) < 2 {
return false
}
return regexp.MustCompile(`(^[\\u4e00-\\u9fa5\\w_—\\-,。…·〔〕()!@¥%……&*?、;‘“]*$)`).MatchString(s)
}
//判断是否是淘宝用户名(子帐号)
func IsSubTaobaoNick(s string) bool {
if len(s) < 2 {
return false
}
return regexp.MustCompile(`(^[\\u4e00-\\u9fa5\\w_—\\-,。…·〔〕()!@¥%……&*?、;‘“:]*$)`).MatchString(s)
}
//判断是否版本号
func IsVersion(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile(`(^[0-9.]*$)`).MatchString(s)
}
//判断是否网址
func IsUrl(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile(`(^[a-zA-z]+://[^\s]*$)`).MatchString(s)
}
//是否数字
func IsNumber(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile(`(^[0-9]*$)`).MatchString(s)
}
//是否多数字(用逗号间隔)
func IsMultipNumber(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile(`(^[0-9,]*$)`).MatchString(s)
}
//判断是否由字母、数字、下划线组成
func IsLetterOrNumber(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile(`(^[A-Za-z0-9_]*$)`).MatchString(s)
}
//判断是否由字母、数字、下划线组成
func IsLetterOrNumber1(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile(`(^[A-Za-z0-9_-]*$)`).MatchString(s)
}
//判断是否由汉字、字母、数字、下划线组成
func IsHanOrLetterOrNumber(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile("^[A-Za-z0-9_\u4e00-\u9fa5-]*$").MatchString(s)
}
//判断是否由汉字、字母、数字、下划线、中杠等组成
func IsGeneralString(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile("^[A-Za-z0-9_\\-#+./:\u4e00-\u9fa5]*$").MatchString(s)
}
//判断是否标准时间格式
func IsStandardTime(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile(`^\d{4}\-\d{2}\-\d{2}\s+\d{2}:\d{2}:\d{2}$`).MatchString(s)
}
// 是否IPv4地址
func IsIPAddress(ip string) bool {
matched, err := regexp.MatchString("(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)", ip)
if err != nil {
return false
}
return matched
}
// 是否内网IP地址
func IsIntranetIP(s string) bool {
matched, err := regexp.MatchString(`^((192\.168|172\.([1][6-9]|[2]\d|3[01]))(\.([2][0-4]\d|[2][5][0-5]|[01]?\d?\d)){2}|10(\.([2][0-4]\d|[2][5][0-5]|[01]?\d?\d)){3})$`, s)
if err != nil {
return false
}
return matched
}
//是否email
func IsEmail(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$").MatchString(s)
}
//是否手机号
func IsMobile(s string) bool {
if len(s) < 1 {
return false
}
return regexp.MustCompile("^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$").MatchString(s)
}
/*
判断字符串是否全中文字符
*/
func IsAllChineseChar(s string) bool {
for _, r := range s {
if !unicode.Is(unicode.Scripts["Han"], r) {
return false
}
}
return true
}
//是否utf-8编码字符串
func IsUtf8(s string) bool {
count := 0
for _, v := range s {
if int(v) > 65530 {
count++
}
}
return count == 0
}
const zip_offset int = 19968
//压缩md5或guid
func ZipMd5(md5String string) (zip_string string, err error) {
if len(md5String) != 16 && len(md5String) != 32 {
return "", errors.New("源md5值长度不对")
}
var md5_bytes []byte
switch len(md5String) {
case 16:
md5_bytes = getHexBytes(md5String + "00")
case 32:
md5_bytes = getHexBytes(md5String + "0")
}
var data bytes.Buffer
var total int = 0
for index := 0; index < len(md5_bytes); index++ {
switch index % 3 {
case 0:
intByte, err := strconv.Atoi(fmt.Sprintf("%d", md5_bytes[index]))
if err != nil {
return zip_string, err
}
total = intByte
break
case 1:
intByte, err := strconv.Atoi(fmt.Sprintf("%d", md5_bytes[index]))
if err != nil {
return zip_string, err
}
total += intByte << 4
break
case 2:
intByte, err := strconv.Atoi(fmt.Sprintf("%d", md5_bytes[index]))
if err != nil {
return zip_string, err
}
total += (intByte << 8) + zip_offset
uni_string := fmt.Sprintf("\\u%x", total)
chinese_string, err := Unicode2String(uni_string)
if err != nil {
return zip_string, err
}
data.WriteString(chinese_string)
total = 0
break
}
}
zip_string = data.String()
return
}
//解压缩汉字,结果为guid或md5值
func UnZipMd5(zip_string string) (md5_string string, err error) {
if len(zip_string) != 18 && len(zip_string) != 33 {
return "", errors.New("源zip值长度不对")
}
var data bytes.Buffer
unicode_string := String2Unicode(zip_string)
unicode_strings := strings.Split(unicode_string, "\\u")
for _, unicode_alue := range unicode_strings {
if strings.EqualFold(unicode_alue, "") {
continue
}
dec, err := strconv.ParseInt(unicode_alue, 16, 32)
if err != nil {
return md5_string, err
}
dec -= int64(zip_offset)
data.WriteString(ten_value_to_char(dec & 15))
data.WriteString(ten_value_to_char((dec >> 4) & 15))
data.WriteString(ten_value_to_char((dec >> 8) & 15))
}
switch len(zip_string) {
case 18:
md5_string = SubString(data.String(), 0, 16)
case 33:
md5_string = SubString(data.String(), 0, 32)
}
return
}
func getHexBytes(str string) []byte {
result := StringToSliceByte(str)
for index := 0; index < len(result); index++ {
if result[index] < 58 {
result[index] -= 48
} else {
result[index] -= 55
}
}
return result
}
func ten_value_to_char(ten int64) string {
switch ten {
case 0, 1, 2, 3, 4, 5, 6, 7, 8, 9:
return strconv.FormatInt(ten, 10)
case 10:
return "A"
case 11:
return "B"
case 12:
return "C"
case 13:
return "D"
case 14:
return "E"
case 15:
return "F"
}
return ""
}
//获取当前内网IP
func GetCurrentIntranetIP() string {
ip_address := ""
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println("获取当前内网IP出错:", err)
return ""
}
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
if strings.HasPrefix(ipnet.IP.String(), "10.") || strings.HasPrefix(ipnet.IP.String(), "192.") {
ip_address = ipnet.IP.String()
break
}
}
}
}
if len(ip_address) < 9 {
fmt.Println("获取当前内网IP出错:没有找到IP")
return ""
}
return ip_address
}
//序列化为json
func ToJson(data interface{}) string {
b, _ := json.Marshal(data)
return string(b)
}
//格式化为Json字符串
func FormatJson(data interface{}) string {
b, err := json.Marshal(data)
if err != nil {
return err.Error()
}
var out bytes.Buffer
err = json.Indent(&out, b, "", "\t")
if err != nil {
return err.Error()
}
return out.String()
}
//序列化-->zlib压缩-->混淆-->base64
func ToJsonZipConfusedBase64(obj interface{}) string {
b, _ := json.Marshal(obj)
b, _ = ZlibZipBytes(b)
b = ConfusedTwo(b)
return Base64(b)
}
//序列化-->混淆-->base64
func ToJsonConfusedBase64(obj interface{}) string {
b, _ := json.Marshal(obj)
b = ConfusedTwo(b)
return Base64(b)
}
//混淆-->zlib压缩-->base64
func ToConfusedZipBase64(str string) string {
b := ConfusedTwo(StringToSliceByte(str))
b, _ = ZlibZipBytes(b)
return Base64(b)
}
//混淆-->base64
func ToConfusedBase64(str string) string {
b := ConfusedTwo(StringToSliceByte(str))
return Base64(b)
}
//生成简单随机密码,短时间内会重复
func GetSimplePwd(lenth int) string {
chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
runes := []rune(chars)
len1 := len(runes)
time.Sleep(time.Millisecond)
math_rand.Seed(time.Now().UnixNano())
pwd := NewStringBuilder()
for index := 0; index < lenth; index++ {
pwd.Append(string(runes[math_rand.Intn(len1)]))
}
return pwd.ToString()
}
//生成随机密码,短时间内会重复
func GetPwd(lenth int) string {
chars := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&*+-=?@^_~'"
runes := []rune(chars)
len1 := len(runes)
time.Sleep(time.Millisecond)
math_rand.Seed(time.Now().UnixNano())
pwd := NewStringBuilder()
for index := 0; index < lenth; index++ {
pwd.Append(string(runes[math_rand.Intn(len1)]))
}
return pwd.ToString()
}