String#delete方法为什么没有从这个字符串中删除连字符(-)字符?

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

Why is String#delete not deleting the `-` char from this string

问题

我试图使用#delete方法清理一些电话号码数据,但根据我的irb测试,只有当我按特定顺序提供参数时,它才会删除'-'字符。

"(941)979- 2000".delete(" -().")仍然保留了-,结果为"941979-2000"

"(941)979- 2000".delete(" ()-.")确实移除了-,结果为"9419792000"

我对这个方法参数要求的理解有什么误解?

英文:

I am trying to sanitise some phone number data by using the #delete method, but according to my testing in irb it is only deleting the '-' character when i present it in a certain order in the argument.

"(941)979- 2000".delete(" -().") still returns with the - present; => "941979-2000"
whereas
"(941)979- 2000".delete(" ()-.") does remove the -; => "9419792000"

What is it that I am misunderstanding about this method's argument requirements?

答案1

得分: 2

根据String#delete的文档,Character Selector -(). 表示:

  • 在空格和(之间的任何字符(这包括空格、!"#$%&'()或
  • )
  • .

也就是说,由这个Character Selector选择的字符集包括空格、!"#$%&'().

Character Selector ()-. 表示:

  • 空格或
  • (
  • ).之间的任何字符(这包括)*+,-.

也就是说,由这个Character Selector选择的字符集包括空格、(*+,-.

换句话说,第一个Character Selector不选择-字符,因为-不在所选字符集中,而第二个Character Selector选择-字符,因为-在所选字符集中。

在不了解您的具体需求的情况下,我猜想您实际需要的Character Selector可能类似于 \-(). ()\-.或简单地是 ().-.

英文:

According to the documentation of String#delete, the Character Selector -(). means:

  • ANY character between and ( (which is , !, ", #, $, %, &, ', and () OR
  • ) OR
  • .

I.e. the set of all characters selected by this Character Selector is , !, ", #, $, %, &, ', (, ), and ..

Whereas the Character Selector ()-. means:

  • OR
  • ( OR
  • ANY character between ) and . (which is ), *, +, ,, -, and .)

I.e. the set of all characters selected by this Character Selector is , (, *, +, ,, -, and .

In other words, the first Character Selector does not select the - character because the - is not present in the set of selected characters whereas the second Character Selector does select the - character because the - is present in the set of selected characters.

Without knowing your precise requirements, my guess is that the Character Selector you actually want is something like \-(). or ()\-. or simply ().-.

huangapple
  • 本文由 发表于 2023年3月9日 21:34:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685333.html
匿名

发表评论

匿名网友

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

确定