简体   繁体   English

正则表达式匹配由 1 个空格或 1 个连字符分隔的单词

[英]Regular Expression matching words separated by 1 space or 1 hyphen

I need to match a string with the following pattern: "ExactWord (Pattern)"我需要匹配具有以下模式的字符串:“ExactWord (Pattern)”

Pattern consists of one or more words, each separated by a single whitespace or a single hyphen.模式由一个或多个单词组成,每个单词由一个空格或一个连字符分隔。 If a whitespace or hyphen is found immediately after open bracket, it should not match.如果在左括号后立即找到空格或连字符,则不应匹配。 If a whitespace or hyphen is found immediately before close bracket it should not match.如果在右括号之前发现空格或连字符,则不应匹配。

My current problem is that I cannot write a pattern that won't match multiple spaces and multiple hyphens:我目前的问题是我无法编写不匹配多个空格和多个连字符的模式:

using System;
using System.Text.RegularExpressions;

namespace Code
{
    public static class Program
    {
        public static void Main()
        {
            string[] str = new string[] { "CorrectWord (black-tailed jackrabbit)",
                "IncorrectWord (saber-tooth)",
                "CorrectWord(animal)", 
                "CorrectWord bird", 
                "CorrectWord (Lion)", 
                "CorrectWordNot (Eagle)", 
                "CorrectWord (Harpy eagle)", 
                "CorrectWord (One Two Three)", 
                "CorrectWord (Too  Many  Spaces)", //should not match, but does.
                "CorrectWord (One-two-three)", 
                "CorrectWord (Too--Many Hypens)", //should not match, but does
                "CorrectWord ( leading-white-space)", 
                "CorrectWord (trailing white space )" 
            };
            foreach (string s in str)
            {
                if (Regex.IsMatch(s, @"^CorrectWord" + Regex.Escape(" (") + @"\w+[\w+(\s|\-)?]+\w+" + Regex.Escape(")") + "$"))
                {
                    Console.WriteLine(s);
                }
            }
        }
    }
}

Output:输出:

CorrectWord (black-tailed jackrabbit)
CorrectWord (Lion)
CorrectWord (Harpy eagle)
CorrectWord (One Two Three)
CorrectWord (Too  Many  Spaces)
CorrectWord (One-two-three)
CorrectWord (Too--Many Hypens)

You can try你可以试试

 \ACorrectWord \([A-Za-z]+(?:[ -][A-Za-z]+)*\)\z

pattern;图案; here这里

 \A            - anchor, string start
  CorrectWord  - correct word as it should be
               - ' ' (space)
 \(            - '('
 [A-Za-z]+     - word (one or more chars in A..Z or a..z range)
 (?: ... )*    - followed by zero or more chunks which are
 [ -][A-Za-z]+ - hyphen or space [ -] then word [A-Za-z]+
 \)            - ')'
 \z            - anchor, end of the string 

Demo:演示:

  string[] str = new string[] { 
    "CorrectWord (black-tailed jackrabbit)",
    "IncorrectWord (saber-tooth)",
    "CorrectWord(animal)",
    "CorrectWord bird",
    "CorrectWord (Lion)",
    "CorrectWordNot (Eagle)",
    "CorrectWord (Harpy eagle)",
    "CorrectWord (One Two Three)",
    "CorrectWord (Too  Many  Spaces)", //should not match, but does.
    "CorrectWord (One-two-three)",
    "CorrectWord (Too--Many Hypens)", //should not match, but does
    "CorrectWord ( leading-white-space)",
    "CorrectWord (trailing white space )"
  };

  Regex regex = new Regex(@"\ACorrectWord \([A-Za-z]+(?:[ -][A-Za-z]+)*\)\z");

  var result = str
    .Select(test => $"{test,-40} :: {(regex.IsMatch(test) ? "match" : "failed")}");

  Console.Write(string.Join(Environment.NewLine, result));

Outcome:结果:

CorrectWord (black-tailed jackrabbit)    :: match
IncorrectWord (saber-tooth)              :: failed
CorrectWord(animal)                      :: failed
CorrectWord bird                         :: failed
CorrectWord (Lion)                       :: match
CorrectWordNot (Eagle)                   :: failed
CorrectWord (Harpy eagle)                :: match
CorrectWord (One Two Three)              :: match
CorrectWord (Too  Many  Spaces)          :: failed
CorrectWord (One-two-three)              :: match
CorrectWord (Too--Many Hypens)           :: failed
CorrectWord ( leading-white-space)       :: failed
CorrectWord (trailing white space )      :: failed

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

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