简体   繁体   English

正则表达式以匹配数字,逗号和特定单词

[英]Regex to match digits, commas, and specific words

I'm trying to set up regex that would match the following: 我正在尝试设置符合以下条件的正则表达式:

hot 8,6,4,2,1,7

This is the code that I have worked on so far, neither of which are specific enough: 到目前为止,这是我一直在研究的代码,但都不够具体:

^(hot)|(cold)|( )([8])
^(hot)|(cold)|([1-8])|(,\d{1})

Here's the requirements that I need to force a check on format: 这是我需要强制检查格式的要求:

  1. The regex should match lower case words, either "hot" or "cold" 正则表达式应匹配小写单词“ hot”或“ cold”
  2. Numbers cannot be outside of range [1-8] 数字不能超出范围[1-8]
  3. If string has either words hot or cold , there has to be a space and an 8 following the space; 如果字符串的单词为hotcold ,则必须在其后有一个空格和8; for example, hot 8 or cold 8 例如, hot 8cold 8
  4. last character in string should end with a number (no space or character) 字符串中的最后一个字符应以数字结尾(无空格或字符)

Some help with this would be immensely appreciated. 在此方面的一些帮助将不胜感激。 Thanks ahead of time! 提前谢谢!

((hot 8,)|(cold 8,))?(/d,)+/d ((hot 8,)|(cold 8,))?(/ d,)+ / d

So I may have miss typed the regex symbols correctly but I'm on a phone and have no quick reference, but I know the rules Exist if that helps. 因此,我可能会错过键入正则表达式符号的正确操作,但是我正在打电话并且没有快速参考,但是我知道规则存在,是否有帮助。 but the explanation is basically.. 但解释基本上是..

“hot space number” or “cold space number” (zero or 1 time) then and amount of numbers followed by a comma (1 or more times) then a final number with no finishing comma. 然后是“热空间编号”或“冷空间编号”(零或1次),数量后跟一个逗号(1次或多次),然后是没有结束逗号的最终数字。

Sorry about my answer formatting... mobile device. 抱歉,我的答案格式...移动设备。

You may use 您可以使用

Regex.IsMatch(s, @"^(?:hot|cold) 8(?:,[1-8])*$")

See the regex demo . 参见regex演示

Explanation : 说明

  • ^ - start of string ^ -字符串的开头
  • (?:hot|cold) - hot or cold substrings (?:hot|cold) - hot还是cold子字符串
    • 8 - space and 8 8空间和8
  • (?:,[1-8])* - zero or more ( * ) occurrences of: (?:,[1-8])* -零个或多个( * )出现:
    • , - a comma , -逗号
    • [1-8] - a digit from 1 to 8 (tune as you see fit here) [1-8] 18的数字(您可以根据自己的喜好进行调整)
  • $ - end of string. $ -字符串结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM