Quantifiers match an item a specified number of times.
Quantifier | Meaning |
---|---|
* | Zero or more matches |
+ | One or more matches |
? | Zero or one match |
{n} | Exactly n matches |
{n,} | At least n matches |
{n,m} | Between n and m matches |
The * quantifier matches the preceding character or group zero or more times.
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Console.Write(Regex.Match("abc1.doc", @"abc\d*\.doc").Success);
}
}
The output:
True
We have to escape out the period in the file extension with a backslash.
The following allows anything between abc and .doc:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Console.Write(Regex.Match("abc123321.doc", @"abc.*\.doc").Success);
}
}
The output:
True
The + quantifier matches the preceding character or group one or more times.
For example:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Console.Write (Regex.Matches ("Yes. Yeeeeeeeeeeeeees", "Ye+s").Count);
}
}
The output:
2
The {} quantifier matches a specified number (or range) of repetitions.
The following matches a blood pressure reading:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Regex bp = new Regex (@"\d{2,3}/\d{2,3}");
Console.WriteLine (bp.Match ("This is a number 10/10"));
Console.WriteLine (bp.Match ("this is another number 1/5"));
}
}
The output:
10/10
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |