Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何匹配字符串的一部分并拒绝整个字符串?_C#_Regex - Fatal编程技术网

C# 如何匹配字符串的一部分并拒绝整个字符串?

C# 如何匹配字符串的一部分并拒绝整个字符串?,c#,regex,C#,Regex,我有一个包含以下四个元素的数组: [0]://一些数据 [1]:一些数据 [2]:对于i=1到10 [3]:foreach i 我要检查四个正则表达式 1) 如果字符串以/开头,而不是/ 2) 如果字符串以/ 3) 如果字符串以开头表示,而不是以开头表示 4) 如果字符串以foreach开头 对于/我使用了^/.,它工作得很好,但我不知道如何匹配/并拒绝/ 对于foreach我使用了^foreach,但我不知道如何仅为匹配 编辑: for和foreach只是示例数据。 它可能只有的,后面可能没有

我有一个包含以下四个元素的数组:
[0]://一些数据

[1]:一些数据

[2]:对于i=1到10
[3]:foreach i

我要检查四个正则表达式
1) 如果字符串以
/
开头,而不是
/

2) 如果字符串以
/

3) 如果字符串以
开头表示
,而不是以
开头表示

4) 如果字符串以
foreach开头

对于
/
我使用了
^/.
,它工作得很好,但我不知道如何匹配
/
并拒绝
/

对于
foreach
我使用了
^foreach
,但我不知道如何仅为
匹配

编辑:
for
foreach
只是示例数据。

它可能只有
,后面可能没有任何内容。

我想使用匹配长度字符串以
/
开头,而不是
/
^/[^/].

字符串以
/
开头:
^/.*

字符串以
开头表示
,而不是以
开头表示
^for\s.*


字符串以
foreach
开头:
^foreach\s.

我不确定当
String
类已经有了一个
StartsWith
方法时为什么需要正则表达式,您可以按原样使用它来满足您的#2和#4需求。对于#1和#3,您可以将其与
结合使用!input.StartsWith
获取结果

以下是您可以使用的扩展方法:

public static class Extensions
{
    public static bool StartsWithThisButNotThat(this string input, string startsWith, 
        string notStartsWith = null)
    {
        if (input == null) return startsWith == null;
        if (startsWith == null) return false;
        if (notStartsWith == null) return input.StartsWith(startsWith);
        return input.StartsWith(startsWith) && !input.StartsWith(notStartsWith);
    }
}
然后,在主代码中,您可以进行如下测试:

private static void Main()
{
    var codeLines = new List<string>
    {
        "//some data",
        "/some data",
        "for i = 1 to 10",
        "foreach i",
    };

    foreach (var codeLine in codeLines)
    {
        Console.WriteLine(codeLine);

        Console.Write(" - starts with / and not //".PadRight(40, '.'));
        Console.WriteLine(codeLine.StartsWithThisButNotThat("/", "//"));

        Console.Write(" - starts with //".PadRight(40, '.'));
        Console.WriteLine(codeLine.StartsWithThisButNotThat("//"));

        Console.Write(" - starts with for and not foreach ".PadRight(40, '.'));
        Console.WriteLine(codeLine.StartsWithThisButNotThat("for", "foreach"));

        Console.Write(" - starts with foreach".PadRight(40, '.'));
        Console.WriteLine(codeLine.StartsWithThisButNotThat("foreach"));

        Console.WriteLine("\n" + new string('-', Console.WindowWidth));
    }

    GetKeyFromUser("\nDone! Press any key to exit...");
}
private static void Main()
{
var代码行=新列表
{
“//一些数据”,
“/一些数据”,
“对于i=1到10”,
“foreach i”,
};
foreach(代码行中的var代码行)
{
控制台写入线(代码线);
Console.Write(“-以/开头,而不是/”。PadRight(40,”);
Console.WriteLine(codeLine.startswiththis而不是that(“/”,“/”);
Console.Write(“-以//”开头)。PadRight(40,”);
Console.WriteLine(代码行。以this开头,但不以this(“/”)开头);
Write(“-以for开头,而不是foreach.PadRight(40,”);
Console.WriteLine(codeLine.startswiththis,notthat(“for”,“foreach”));
Write(“-以foreach.PadRight开头(40,”);
Console.WriteLine(codeLine.startswiththis,notthat(“foreach”));
Console.WriteLine(“\n”+新字符串('-',Console.WindowWidth));
}
GetKeyFromUser(“\n完成!按任意键退出…”);
}
输出


像这样的事情应该对你有帮助:

class PatternMatch
{
  public string Prefix { get; private set; }
  public string Suffix { get; private set; }

  private static Regex rxValid = new Regex(@"
    ^                           # start of line, followed by
    (?<pfx>                     # one of...
    ( /  ( [^/] | (?= $ ) ) ) # a slash (but not slash slash!)
    | ( //                    ) # two slashes
    | ( for(?! each )         ) # for (but not foreach)
    | ( foreach               ) # foreach
    )                           # , followed by...
    (?<sfx> .* )                # zero or more extraneous characters, followed by
    $                           # end-of-line  
  ", RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);

  public static PatternMatch TryMatch( string s)
  {
    Match m = rxValid.Match(s);
    PatternMatch instance = m.Success ? new PatternMatch(m) : null ;
    return instance;
  }
  private PatternMatch(Match m)
  {
    if (!m.Groups["pfx"].Success | !m.Groups["sfx"].Success) throw new ArgumentOutOfRangeException("m", "The match needs to be successfull");
    this.Prefix = m.Groups["pfx"].Value;
    this.Suffix = m.Groups["sfx"].Value;
  }
}

如果我想要一部分文本,比如
te
,而不是
test
,那该怎么办?那么你必须更明确地知道你的字符串中有什么样的数据。我不知道任何正则表达式,是\s的意思是空格吗?
\s
是空格。它可以是\t\n\r,也可以只是一个空格。或者,您可以使用
^for\b.*
来匹配而不是foreach。它可能只是
for
,例如,我使用
for
foreach
。您正在尝试用regex解析语言吗?也许解析器更合适。不,这只是一个例子!对于2和4,您可以使用
string
类的
.StartsWith()
方法。是的,我知道,但在我的例子中,我有一个正则表达式数组和一个循环来检查哪个模式匹配,这就是我需要拒绝的原因。我正在阅读,我认为
^((For)|(?!foreach))
可以工作,但它没有成功<代码>(for(?!each))
是我想要的。
^/[^/]
上的
/test
/[SPACE]
给了我
/t
/[SPACE]
,我用了
^/(?!/)
来代替,这行吗?我有一个模式列表要检查,我在找到这四个模式时遇到了问题,实际上我不知道如何使用
(?!xxx)
static void Test()
{
  string[] text =
  {
    "//some data",
    "/some data",
    "for i = 1 to 10",
    "foreach i",
  };

  foreach (string s in text)
  {
    PatternMatch pm = PatternMatch.TryMatch(s);
    if (pm == null)
    {
      Console.WriteLine("NO MATCH: {0}", s);
    }
    else
    {
      Console.WriteLine("MATCHED:  {0}", s);
      Console.WriteLine("  Prefix: len={0}, value={1}", pm.Prefix.Length, pm.Prefix );
      Console.WriteLine("  Suffix: len={0}, value={1}", pm.Suffix.Length, pm.Suffix ); 
    }

  }
}