Регулярные выражения C # - возможно ли извлечь совпадения при сопоставлении?

Вы можете попробовать это

<script type="text/javascript">

var str="$1,112.12";
str = str.replace(",","");
str = str.replace("$","");
document.write(parseFloat(str));

</script>
23
задан Peter Mortensen 8 March 2010 в 14:06
поделиться

3 ответа

You can use regex groups to accomplish that. For example, this regex:

(\d\d\d)-(\d\d\d\d\d\d\d)

Let's match a telephone number with this regex:

var regex = new Regex(@"(\d\d\d)-(\d\d\d\d\d\d\d)");
var match = regex.Match("123-4567890");
if (match.Success)
    ....

If it matches, you will find the first three digits in:

match.Groups[1].Value

And the second 7 digits in:

match.Groups[2].Value

P.S. In C#, you can use a @"" style string to avoid escaping backslashes. For example, @"\hi\" equals "\\hi\\". Useful for regular expressions and paths.

P.S.2. The first group is stored in Group[1], not Group[0] as you would expect. That's because Group[0] contains the entire matched string.

66
ответ дан 28 November 2019 в 22:12
поделиться

You can use parentheses to capture groups of characters:

string test = "RR1234566-001";

// capture 2 letters, then 7 digits, then a hyphen, then 1 or more digits
string rx = @"^([A-Za-z]{2})(\d{7})(\-)(\d+)$";

Match m = Regex.Match(test, rx, RegexOptions.IgnoreCase);

if (m.Success)
{
    Console.WriteLine(m.Groups[1].Value);    // RR
    Console.WriteLine(m.Groups[2].Value);    // 1234566
    Console.WriteLine(m.Groups[3].Value);    // -
    Console.WriteLine(m.Groups[4].Value);    // 001
    return true;
}
else
{
    return false;
}
13
ответ дан 28 November 2019 в 22:12
поделиться

Use grouping and Matches instead.

I.e.:

// NOTE: pseudocode.
Regex re = new Regex("(\\d+)-(\\d+)");
Match m = re.Match(stringToMatch))

if (m.Success) {
  String part1 = m.Groups[1].Value;
  String part2 = m.Groups[2].Value;
  return true;
} 
else {
  return false;
}

You can also name the matches, like this:

Regex re = new Regex("(?<Part1>\\d+)-(?<Part2>\\d+)");

and access like this

  String part1 = m.Groups["Part1"].Value;
  String part2 = m.Groups["Part2"].Value;
17
ответ дан 28 November 2019 в 22:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: