正则表达式以获取“-”之前的所有字符 [英] Regular Expression to get all characters before "-"

查看:631
本文介绍了正则表达式以获取“-”之前的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用正则表达式获取字符- 之前的字符串?

How can I get the string before the character "-" using regular expressions?

例如,我有 text-1 ,我想返回 text

For example, I have "text-1" and I want to return "text".

推荐答案

所以我看到实现这一目标的很多可能性。

So I see many possibilities to achieve this.

string text = "Foobar-test";




  1. 正则表达式匹配所有内容,直到第一个-

  1. Regex Match everything till the first "-"

Match result = Regex.Match(text, @"^.*?(?=-)");




  • ^ 从字符串开头匹配

  • 。*?匹配任何字符(),零次或多次( * ),但次数尽可能少(

  • (?=-)直到下一个字符为-(这是一个积极的眼光)

    • ^ match from the start of the string
    • .*? match any character (.), zero or more times (*) but as less as possible (?)
    • (?=-) till the next character is a "-" (this is a positive look ahead)
    • 正则表达式从字符串开头匹配不是-的任何内容

      Regex Match anything that is not a "-" from the start of the string

      Match result2 = Regex.Match(text, @"^[^-]*");
      




      • [^-] * 匹配不为-零次或多次的任何字符

        • [^-]* matches any character that is not a "-" zero or more times
        • 正则表达式匹配不匹配的任何字符从字符串开头到-

          Regex Match anything that is not a "-" from the start of the string till a "-"

          Match result21 = Regex.Match(text, @"^([^-]*)-");
          

          仅在字符串中包含破折号的情况下才会匹配,但是结果将在捕获组中找到1。

          Will only match if there is a dash in the string, but the result is then found in capture group 1.

          分割为-

          string[] result3 = text.Split('-');
          

          结果是数组,第一个-之前的部分是数组中的第一项

          Result is an Array the part before the first "-" is the first item in the Array

          子字符串,直到第一个-

          Substring till the first "-"

          string result4 = text.Substring(0, text.IndexOf("-"));
          

          从开始到第一次出现-( text.IndexOf(-)

          Get the substring from text from the start till the first occurrence of "-" (text.IndexOf("-"))

          结果(都相同)

          Console.WriteLine(result);
          Console.WriteLine(result2);
          Console.WriteLine(result21.Groups[1]);
          Console.WriteLine(result3[0]);
          Console.WriteLine(result4);
          

          我更喜欢第一种方法。

          当字符串中没有破折号时,您还需要考虑行为。在这种情况下,第四个方法将引发异常,因为 text.IndexOf(-)将为 -1 。方法1和2.1将不返回任何内容,方法2和3将返回完整的字符串。

          You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-") will be -1. Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string.

          这篇关于正则表达式以获取“-”之前的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆