将正则表达式解析字符串转换为环境变量。

huangapple go评论78阅读模式
英文:

go regex parsing string to environment variable

问题

我有一个字符串,我正在尝试使用go regexp进行解析,并将其转换为os.Getenv(env)。假设我们在Go中有字符串"hello world -p $PATH -f $HOSTNAME ",我们想使用正则表达式读取os.Getenv("PATH")os.Getenv("HOSTNAME")。有人可以帮我提供一个适当的正则表达式解析器,以提取出"$"以及将其作为参数传递给os.Getenv()以获取环境变量吗?

英文:

I have a string that I am trying parse using go regexp and convert to os.Getenv(env). Assuming we have string "hello world -p $PATH -f $HOSTNAME " in Go, and want to use regexp to read os.Getenv("PATH") and os.Getenv("HOSTNAME"). Anyone can help me with a proper regexp parser that will extract out "$" along with the word pass it through the os.Getenv() as the parameter for getting the environment variable?

答案1

得分: 3

os.ExpandEnv 函数根据环境变量中的值,替换字符串中的 $var 或 ${var}。我建议使用这个函数,而不是自己使用正则表达式来实现。

英文:

The os.ExpandEnv function replaces $var or ${var} in a string according to the values in the environment. I recommend using this function instead of writing your own using regular expressions.

huangapple
  • 本文由 发表于 2014年9月22日 06:17:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/25964440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定