Skip to content

Instantly share code, notes, and snippets.

@zwjzxh520
Last active April 18, 2016 15:45
Show Gist options
  • Save zwjzxh520/f04bc7d984f54ea83d1c8bf2faabd60e to your computer and use it in GitHub Desktop.
Save zwjzxh520/f04bc7d984f54ea83d1c8bf2faabd60e to your computer and use it in GitHub Desktop.
//消除文件中的注释内容。支持以下两种格式
//1. 以//开头单行注释
//2. /**/块级注释
//可用于清除配置文件中的注释
package comment
func ClearLine(text []byte) []byte {
newText := []byte("")
n := byte('\n')
r := byte('\r')
space := byte(' ')
slash := byte('/')
// line : 0 表示开始新的一行了
// line : 1 表示检测到了新行以注释符开始的标记,比如/符号
// line : 2 检测到以/开头,但不是注释
// line : 3 表示确认本行不是注释,
// line : 4 确认本行是注释
line := 0
for _, v := range text {
if line == 1 {
if v != slash {
newText = append(newText, slash)
newText = append(newText, v)
line = 2
} else {
line = 4
}
} else if v == slash && line == 0 {
line = 1
} else if v == n || v == r {
line = 0
newText = append(newText, v)
} else if v == space {
if line == 3 {
newText = append(newText, v)
}
} else if line != 4 {
newText = append(newText, v)
line = 3
}
}
return newText
}
func ClearSection(text []byte) []byte {
newText := []byte("")
n := byte('\n')
r := byte('\r')
space := byte(' ')
slash := byte('/')
asterisk := byte('*')
// line : 0 表示开始新的一行并且不需要检测块注释的结束符
// line : 1 表示检测到了新行以注释符开始的标记,比如/符号
// line : 3 表示确认本行不是注释,
// line : 4 确认本行是注释
line := 0
// section : 0 不处于块注释结束符判断当中
// section : 1 检测到*,需要检测到/符号,以结束块注释判断
section := 0
for _, v := range text {
//检测到上一个字符是/,并且位于行首
if line == 1 {
if v != asterisk {
newText = append(newText, slash)
newText = append(newText, v)
line = 2
} else {
line = 4
}
} else if v == slash && line == 0 {
line = 1
} else if v == n || v == r {
if line != 4 {
line = 0
}
newText = append(newText, v)
} else if v == space {
if line == 3 {
newText = append(newText, v)
}
} else if line != 4 {
newText = append(newText, v)
line = 3
} else if line == 4 {
//检测块注释的结束符*/
if v == asterisk {
section = 1
} else if section == 1 && v == slash {
section = 0
line = 3
} else {
section = 0
}
}
}
return newText
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment