简体   繁体   English

C#正则表达式匹配文本直到特定字符

[英]C# Regex Match text until specific character

I'm trying to get a regex to validate/extract from a string all the characters until the first dollar. 我试图得到一个正则表达式来验证/提取字符串中的所有字符,直到第一美元。 If the string doesn't have any dollar,it should match the whole string but it doesn't work. 如果字符串没有任何美元,则应与整个字符串匹配,但不起作用。

What i tested is: 我测试的是:

System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match("12345678$1", "/[^\$]*/");

What i expect is to get in match.value => 12345678 If the string passed is for example 123456781 it should return everything. 我期望得到的是match.value => 12345678如果传递的字符串是例如123456781,则它应该返回所有内容。

What is wrong? 怎么了?

Thanks Best regards. 致以最诚挚的问候。

You forget to escape your \\ : 您忘了逃避\\

Match match = Regex.Match("12345678$1", "[^\\$]*");
Console.WriteLine(match.Value);
match = Regex.Match("123456781", "[^\\$]*");
Console.WriteLine(match.Value);

Outputs: 输出:

12345678
123456781

As pointed out by dolgsthrasir you don't need to escape $ in your regexp so "[^$]*" is fine. 正如dolgsthrasir指出的那样,您无需在正则表达式中转义$ ,因此"[^$]*"就可以了。

Try with this 试试这个

System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match("12345678$1", "([^\\$]+)");

extracted string should be group 1. 提取的字符串应为组1。

From what I am getting, the expression you are using will match any string which is made up from 0 or more instances of any non $ character. 从我得到的结果来看,您正在使用的表达式将匹配由0个或多个任何非$实例组成的字符串。

You could try something like below: 您可以尝试以下操作:

        string sample = "1234578";
        Regex regex = new Regex("(.+?)(\\$|$)");
        if (regex.IsMatch(sample))
        {
            Match match = regex.Match(sample);
            Console.WriteLine(match.Groups[1]);
        }

Which matches and extracts any numbers up to $ (denoted as \\\\$ ) or else, the end of the string (denoted by $ ), which ever comes first. 它将匹配并提取任何数字,直到$ (表示为\\\\$ ),否则将提取字符串的末尾(表示为$ ),以先到者为准。

You don't need regex, you can just use IndexOf and SubString 您不需要正则表达式,只需使用IndexOfSubString

var str = "12345678$1";
int index = str.IndexOf("$");
if(index < 0)
    return str;
else
    return str.Substring(0, index);

Example

System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match("12345678$1", "(.+)\\$");

您的结果将在match.Groups [1]中

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

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