Go语言中如何基于单/双关键字正确分组匹配Zephir属性声明
解决Zephir属性声明正则匹配问题(Go语言环境)
正则表达式写法
^(\s*(?:public|protected|private)(?:\s+static)?\s+)([a-zA-Z_]\w*(?:\s*=\s*.+)?)\s*;
正则说明
- 分组1:捕获属性的修饰符部分,包含行首缩进空白、必选的访问修饰符(
public/protected/private)、可选的static关键字,以及修饰符与属性名之间的空白。 - 分组2:捕获属性的核心声明内容,包含符合标识符规则的属性名(以字母/下划线开头,后跟字母、数字、下划线)、可选的赋值语句。正则通过属性名的规则限制,自动排除
public static function xxx()这类方法声明行,避免误匹配。
Go语言使用示例
package main import ( "regexp" "strings" ) func main() { zephirLines := []string{ " protected _email;", " public static _maxCount = 100;", " private function getValue() {}", // 不会被匹配 } re := regexp.MustCompile(`^(\s*(?:public|protected|private)(?:\s+static)?\s+)([a-zA-Z_]\w*(?:\s*=\s*.+)?)\s*;`) for _, line := range zephirLines { match := re.FindStringSubmatch(line) if len(match) != 3 { continue } // 为属性名添加$符号 parts := strings.SplitN(match[2], "=", 2) propName := "$" + strings.TrimSpace(parts[0]) propContent := propName if len(parts) == 2 { propContent += " = " + strings.TrimSpace(parts[1]) } phpLine := match[1] + propContent + ";" println(phpLine) } }
补充说明
- 若需兼容
static public这类不规范修饰符顺序,可将分组1调整为(\s*(?:(public|protected|private)\s+static|static\s+(public|protected|private))\s+)。 - 对于行尾带注释的属性声明(如
protected _id; // user ID),正则会保留注释部分,不影响属性转换逻辑。 - 批量处理文件时,建议先通过语法分析定位类内部代码块,再用正则匹配属性行,进一步降低误匹配概率。
内容的提问来源于stack exchange,提问作者JMoodyFWD
相关产品推荐
相关产品推荐

