英文:
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
(
(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- 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 ().-
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论