J. Davidson
J. Davidson

Reputation: 3307

Regular Expression to match certain formula

I am new to regular expression. I was wondering how I can use regular expression to replace

001-34/323
To 
001/34-323

I have something like this

 return Regex.Replace(input, 
               "\\b(?<p1>\\d{1,2})/(?<p2>\\d{1,2})/(?<p6>\\d{2,4})\\b",
               "${p1}-${p2}-${p3}", RegexOptions.None.

I have something like this but it doesn't work it does the opposite of what I want

input has all integers. Please let me know the regular expression that will change the input to the output Thanks

Upvotes: 2

Views: 73

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31686

Why make it hard by trying to match the pattern of the data?

If you are just replacing a dash with a slash, use the match evaluator to return the opposite upon finding the dash or slash.

var text = "001-34/323";

Regex.Replace(text, "[-/]", me => { return me.Value == "-" ? "/" : "-";   })

Result

001/34-323

Upvotes: 0

ProgrammingLlama
ProgrammingLlama

Reputation: 38785

Your current regular expression expects a number like this:

P1/P2/P3

Where:

  • P1 is a 1-2 digit number
  • P2 is a 1-2 digit number
  • P3 is a 2-4 digit number

Why isn't it working? Your input string is 001-34/323 (P1-P2/P3) and P1 is a 3 digit number. Additionally, your last capture group is called <p6>, not <p3>.

The correct string should be:

\b(?<p1>\d{1,3})-(?<p2>\d{1,2})/(?<p3>\d{2,4})\b

Or in escaped form:

"\\b(?<p1>\\d{1,3})-(?<p2>\\d{1,2})/(?<p3>\\d{2,4})\\b",

Your template for the output is also wrong (P1-P2-P3, not P1/P2-P3).

Final code example:

var input = "001-34/323";
var output = Regex.Replace(input, 
                   "\\b(?<p1>\\d{1,3})-(?<p2>\\d{1,2})/(?<p3>\\d{2,4})\\b",
                   "${p1}/${p2}-${p3}",
                   RegexOptions.None);
Console.WriteLine(output);

Try it online

Upvotes: 2

Related Questions