检查字符串是否至少包含 R 中的一个数字字符

问题描述:

我尝试了以下方法,但是,当字符串包含任何其他字符(例如空格)时会出错.如下图所示,有一个字符串叫做subway 10",里面确实包含数字字符,但是因为空格而报错.

I have tried the following, however, it goes wrong when the string contains any other character, say a space. As you can see below, there is a string called "subway 10", which does contain numeric characters, however, it is reported as false because of the space.

我的字符串可能包含任何其他字符,但如果它至少包含一个数字,我想从数组中获取这些字符串的索引.

My string may contain any other character, but if it contains at least a single digit, I would like to get the indices of those strings from the array.

> mywords<- c("harry","met","sally","subway 10","1800Movies","12345")
> numbers <- grepl("^[[:digit:]]+$", mywords) 
> letters <- grepl("^[[:alpha:]]+$", mywords) 
> both <- grepl("^[[:digit:][:alpha:]]+$", mywords) 
> 
> mywords[xor((letters | numbers), both)] # letters & numbers mixed 
[1] "1800Movies"

using \\d 对我有用:

using \\d works for me:

grepl("\\d", mywords)
[1] FALSE FALSE FALSE  TRUE  TRUE  TRUE

[[:digit:]]:

grepl("[[:digit:]]", mywords)
[1] FALSE FALSE FALSE  TRUE  TRUE  TRUE

正如@nrussel 提到的,您正在测试字符串是否只包含字符串开头 ^ 到结尾 $ 之间的数字.

As @nrussel mentionned, you're testing if the strings contain only digits between the beginning ^ of the string till the end $.

您还可以检查字符串是否包含字母以外的其他内容,使用括号内的 ^ 来否定字母,但其他内容"不仅是数字:

You could also check if the strings contain something else than letters, using ^ inside brackets to negate the letters, but then "something else" is not only digits:

grepl("[^a-zA-Z]", mywords)
[1] FALSE FALSE FALSE  TRUE  TRUE  TRUE