英文:
Remove first occurence of match in regex golang
问题
我有以下字符串:
new k8s.KubeRoleBinding(this, "argocd-application-controller", {
kind: "RoleBinding",
metadata: {
labels: {
"app.kubernetes.io/component": "application-controller",
"app.kubernetes.io/name": "argocd-application-controller",
"app.kubernetes.io/part-of": "argocd",
},
name: "argocd-application-controller",
},
roleRef: {
apiGroup: "rbac.authorization.k8s.io",
kind: "Role",
name: "argocd-application-controller",
},
subjects: [{
kind: "ServiceAccount",
name: "argocd-application-controller",
}],
});
我想删除第一个出现的 kind:
的行。
到目前为止,我尝试了以下方法,但它会删除所有出现的行。
re := regexp.MustCompile(`(?m)[\r\n]+^.*kind.*$`)
res := re.ReplaceAllString(str, "")
希望得到的字符串是:
new k8s.KubeRoleBinding(this, "argocd-application-controller", {
metadata: {
labels: {
"app.kubernetes.io/component": "application-controller",
"app.kubernetes.io/name": "argocd-application-controller",
"app.kubernetes.io/part-of": "argocd",
},
name: "argocd-application-controller",
},
roleRef: {
apiGroup: "rbac.authorization.k8s.io",
name: "argocd-application-controller",
},
subjects: [{
kind: "ServiceAccount",
name: "argocd-application-controller",
}],
});
英文:
I have the following string:
new k8s.KubeRoleBinding(this, "argocd-application-controller", {
kind: "RoleBinding",
metadata: {
labels: {
"app.kubernetes.io/component": "application-controller",
"app.kubernetes.io/name": "argocd-application-controller",
"app.kubernetes.io/part-of": "argocd",
},
name: "argocd-application-controller",
},
roleRef: {
apiGroup: "rbac.authorization.k8s.io",
kind: "Role",
name: "argocd-application-controller",
},
subjects: [{
kind: "ServiceAccount",
name: "argocd-application-controller",
}],
});
Id like to remove the line which has the first occurence of kind:
I tried the following so far, but it removes all occurrences.
re := regexp.MustCompile("(?m)[\r\n]+^.*kind.*$")
res := re.ReplaceAllString(str, "$1")
Playground link with code : https://play.golang.org/p/SMiyTJvKNVF
Wanted string :
new k8s.KubeRoleBinding(this, "argocd-application-controller", {
metadata: {
labels: {
"app.kubernetes.io/component": "application-controller",
"app.kubernetes.io/name": "argocd-application-controller",
"app.kubernetes.io/part-of": "argocd",
},
name: "argocd-application-controller",
},
roleRef: {
apiGroup: "rbac.authorization.k8s.io",
kind: "Role",
name: "argocd-application-controller",
},
subjects: [{
kind: "ServiceAccount",
name: "argocd-application-controller",
}],
});
答案1
得分: 2
找到第一个匹配项的位置。使用字符串切片操作删除匹配项。
loc := re.FindStringIndex(str)
res := str
if loc != nil {
res = str[:loc[0]] + str[loc[1]:]
}
英文:
Find the location of the first match. Use string slice operations to delete the match.
loc := re.FindStringIndex(str)
res := str
if loc != nil {
res = str[:loc[0]] + str[loc[1]:]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论