2011-11-24 193 views
1

我想用正则表达式来检查,如果我的字符串的格式类似如下:字符串格式检查(有部分随机字符串)

mc_834faisd88979asdfas8897asff8790ds_oa_ids 
mc_834fappsd58979asdfas8897asdf879ds_oa_ids 
mc_834faispd8fs9asaas4897asdsaf879ds_oa_ids 
mc_834faisd8dfa979asdfaspo97asf879ds_dv_ids 
mc_834faisd111979asdfas88mp7asf879ds_dv_ids 
mc_834fais00979asdfas8897asf87ggg9ds_dv_ids 

的格式是这样mc_<random string>_oa_idsmc_<random string>_dv_ids。如何检查我的字符串是否处于这两种格式之一?请解释正则表达式。谢谢。

这是一个字符串的开始与mc_,而与_oa_idsdv_ids,并最终在中间有一些随机字符串

P.S.随机字符串由alpha-beta字母和数字组成。

我试了一下(我不知道如何检查随机字符串):

/^mc_834faisd88979asdfas8897asff8790ds$_os_ids/ 
+2

我不知道如何检查随机字符串,我怎么可以尝试用不知道???这就是为什么我在这里问...... –

回答

5

试试这个。

^mc_[0-9a-z]+_(dv|oa)_ids$ 

^   matches at the start of the line the regex pattern is applied to. 
[0-9a-z] matces alphabetic and numeric chars. 
+   means that there should be one or more chars in this set 
(dv|oa)  matches dv or oa 
$   matches at the end of the string the regex pattern is applied to. 
    also matches before the very last line break if the string ends with a line break. 
+0

如果需要这种精确度,OP可以放置'{33}'而不是'+'。 – deviousdodo

+0

'^'和'$'不是字符串的开始和结尾,它们是行的开始和结束。 – tbuehlmann

+0

如果我在ruby代码中检查字符串格式,我需要添加//像mystr ==/^ mc_ [0-9a-z] + _(dv | oa)_ids $ /? –

0

/\Amc_\w*_(oa|dv)_ids\z/一试。 \A是字符串的开始,\z结束。 \w*是一个或多个字母,数字和下划线,(oa|dv)oadv

测试Ruby正则表达式的一个很好且简单的方法是Rubular,可能看看它。