检查字符串是否至少包含 R 中的一个数字字符 [英] Check if a string contains at least one numeric character in R

查看:38
本文介绍了检查字符串是否至少包含 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

这篇关于检查字符串是否至少包含 R 中的一个数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆