确保字符串开头只有一个冒号。

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

Ensuring a single colon at start of string

问题

我正在使用getopts来解析选项。我想确保optstring在开头只有一个冒号,如果不存在,我想引入它。

以下是optstring的初始化示例:

local optstring="sn:z:"
英文:

I am using getopts to parse options. I want to ensure that the optstring has only a single colon at the start, and if this does not exist I want to introduce it.

Here is an example of the initialisation of optstring

  local optstring="sn:z:" 

答案1

得分: 1

这是与POSIX兼容的代码(在Bash和Dash中进行了测试),处理字符串开头的任意数量的冒号:

optstring=:${optstring#${optstring%%[!:]*}}
  • ${optstring%%[!:]*} 展开为 $optstring 开头的冒号字符串(可能为空)。这是通过删除第一个非冒号字符([!:])及其后的所有内容来实现的。
  • ${optstring#${optstring%%[!:]*}} 展开为删除了开头所有冒号的 $optstring

这个转换可以分为两个步骤来执行,以增加可读性(可能):

colons=${optstring%%[!:]*}
optstring=:${optstring#$colons}

另一种(也与POSIX兼容的)方法是使用循环删除开头的冒号:

while [ "${optstring#:}" != "$optstring" ]; do
    optstring=${optstring#:}
done
optstring=:$optstring
英文:

This POSIX-compatible code (tested with Bash and Dash) handles arbitrary numbers of colons at the start of the string:

optstring=:${optstring#${optstring%%[!:]*}}
  • ${optstring%%[!:]*} expands to the (possibly empty) string of colons at the start of $optstring. It does this by removing the first non-colon character ([!:]) and everything that follows it.
  • ${optstring#${optstring%%[!:]*}} expands to $optstring with all the colons at the start removed.

The transformation can be done in two steps to (possibly) make it more readable:

colons=${optstring%%[!:]*}
optstring=:${optstring#$colons}

Another (also POSIX-compatible) approach is to use a loop to remove leading colons:

while [ "${optstring#:}" != "$optstring" ]; do
    optstring=${optstring#:}
done
optstring=:$optstring

答案2

得分: 0

首先,我们无条件地添加一个冒号,然后我们使用参数扩展来扩展我们的字符串,删除任何已存在的冒号。
英文:
optstring=:${optstring#:}

First we unconditionally add a colon, then we use a parameter expansion to expand our string with any preexisting colon removed.

huangapple
  • 本文由 发表于 2023年5月7日 22:16:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194470.html
匿名

发表评论

匿名网友

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

确定