chung pham nhu
chung pham nhu

Reputation: 335

Parse Name in A string

How to use regex to match this in C#?

1.1 or 2.1 or 1.I/3 or 1.C/1

That mean the string begin with a number, followed by a dot (.) , then followed by a number or a character C, I (or any letter A - Z), then followed by a splash(/), then a number

I have tried this expression, but it doesn't work.

string patternName = @"\d\.(\d|I/\d|C/\d)";

Upvotes: 2

Views: 160

Answers (3)

Johnny
Johnny

Reputation: 491

Use this pattern (updated):

\d\.[\dIC]\/?\d?

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149020

You're very close. Try this:

string patternName = @"\d\.(?:\d|[A-Z]/\d)";

Or more simply

string patternName = @"\d\.(?:[A-Z]/)?\d";

If you want to allow more than one digit (e.g. 1.10 or 2.I/22), use a one-or-more (+) qunatifier:

string patternName = @"\d+\.(?:[A-Z]/)?\d+";

For example:

string input = "1.1NGUYEN/VAN DUONG MR 2.1NGUYEN/THI ANH MRS 3.I/1NGUYEN/THI NHU QUYNH";
string patternName = @"\d+\.(?:[A-Z]/)?\d+";
string[] output = Regex.Split(input, patternName);
// [ "", "NGUYEN/VAN DUONG MR ", "NGUYEN/THI ANH MRS ", "NGUYEN/THI NHU QUYNH" ]

Upvotes: 1

Sujith PS
Sujith PS

Reputation: 4864

You can use :

(\d+\.(?:\d+|C|I)(?:\/\d+)?)

DEMO

EXPLANATION

enter image description here

Upvotes: 1

Related Questions