1

I would like to use regular expression to check if my string have the format like following:

mc_834faisd88979asdfas8897asff8790ds_oa_ids
mc_834fappsd58979asdfas8897asdf879ds_oa_ids
mc_834faispd8fs9asaas4897asdsaf879ds_oa_ids
mc_834faisd8dfa979asdfaspo97asf879ds_dv_ids
mc_834faisd111979asdfas88mp7asf879ds_dv_ids
mc_834fais00979asdfas8897asf87ggg9ds_dv_ids

The format is like mc_<random string>_oa_ids or mc_<random string>_dv_ids . How can I check if my string is in either of these two formats? And please explain the regular expression. thank you.

That's a string start with mc_, while end with _oa_ids or dv_ids, and have some random string in the middle.

P.S. the random string consists of alpha-beta letters and numbers.

What I tried(I have no clue how to check the random string):

/^mc_834faisd88979asdfas8897asff8790ds$_os_ids/
1
  • 2
    I have no clue how to check the random string, how can I try with no clue??? That's why I ask here....
    – Leem.fin
    Nov 24, 2011 at 14:54

3 Answers 3

5

Try this.

^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.
5
  • The OP can put {33} instead of + if needs that kind of precision. Nov 24, 2011 at 15:10
  • ^ and $ are not the start and end of a string, they are the start and end of a line.
    – tbuehlmann
    Nov 24, 2011 at 15:10
  • if I check the string format in ruby code, do I need to add // like mystr==/^mc_[0-9a-z]+_(dv|oa)_ids$/ ?
    – Leem.fin
    Nov 24, 2011 at 15:15
  • @tbuehlmann true. That depends what you are trying to match. It can be a file's or a line's start and end too.
    – tuze
    Nov 24, 2011 at 15:16
  • @Leem.fin Yes you need to. s = "mc_834faisd88979asdfas8897asff8790ds_oa_ids" r = /^mc_[0-9a-z]+_(dv|oa)_ids$/ m = r.match s
    – tuze
    Nov 24, 2011 at 15:27
0

Give /\Amc_\w*_(oa|dv)_ids\z/ a try. \A is the beginning of the string, \z the end. \w* are one or more of letters, numbers and underscores and (oa|dv) is either oa or dv.

A nice and simple way to test Ruby Regexps is Rubular, might have a look at it.

0

This should work

/mc_834([a-z,0-9]*)_(oa|dv)_ids/g

Example: http://regexr.com?2v9q7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.