【问题标题】:string format checking (with partly random string)字符串格式检查(部分随机字符串)
【发布时间】:2011-11-24 23:48:46
【问题描述】:

我想使用正则表达式来检查我的字符串是否具有如下格式:

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/

【问题讨论】:

  • 我不知道如何检查随机字符串,我如何在没有线索的情况下尝试???这就是为什么我在这里问....

标签: ruby-on-rails ruby regex


【解决方案1】:

试试这个。

^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.

【讨论】:

  • 如果需要这种精度,OP 可以使用{33} 而不是+
  • ^$ 不是字符串的开头和结尾,它们是一行的开头和结尾。
  • 如果我检查 ruby​​ 代码中的字符串格式,是否需要添加 // like mystr==/^mc_[0-9a-z]+_(dv|oa)_ids$/ ?
  • @tbuehlmann 是真的。这取决于您要匹配的内容。它也可以是一个文件或一行的开始和结束。
  • @Leem.fin 是的,你需要。 s = "mc_834faisd88979asdfas8897asff8790ds_oa_ids" r = /^mc_[0-9a-z]+_(dv|oa)_ids$/ m = r.match s
【解决方案2】:

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

Rubular 是测试 Ruby Regexps 的一种简单而好用的方法,不妨看看。

【讨论】:

    【解决方案3】:

    这应该可以工作

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

    示例:http://regexr.com?2v9q7

    【讨论】:

      猜你喜欢
      • 2019-04-22
      • 2013-02-04
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多