简体   繁体   中英

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"
  2. Numbers cannot be outside of range [1-8]
  3. If string has either words hot or cold , there has to be a space and an 8 following the space; for example, hot 8 or cold 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

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.

Sorry about my answer formatting... mobile device.

You may use

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

See the regex demo .

Explanation :

  • ^ - start of string
  • (?:hot|cold) - hot or cold substrings
    • 8 - space and 8
  • (?:,[1-8])* - zero or more ( * ) occurrences of:
    • , - a comma
    • [1-8] - a digit from 1 to 8 (tune as you see fit here)
  • $ - end of string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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