3
\$\begingroup\$

I am searching a string for a pattern that matches Material=. Some examples are Material=ABC123,Color=444555, Material=332212,Color=192929 I am new to C# and I learned about capture groups but I am wondering if its possible to do it in a cleaner way?

var pattern = new Regex("(?<label>Material)=(?<value>[^,]+)");
Match match = pattern.Match(Row2.Attributes);
var materialCode = (match.Success) ? match.Groups["value"].Value : "NA";

Edit:

I store materialCode into a database so it can't be null. If a value isn't found it has to be "NA". Also there are lots of combos which is why I specify I need whatever value after the = but before the , in the regex

asked Jan 10, 2018 at 18:30
\$\endgroup\$
1
  • \$\begingroup\$ That looks like the right way to me. \$\endgroup\$ Commented Feb 9, 2018 at 23:35

1 Answer 1

3
\$\begingroup\$

Do not set the materialCode to another string. I am not sure, but NA might also be a valid choice for Material=<value>. Instead, just set it to null.

As for the pattern itself, instead of searching for [^,] (anything except ,), you should look for only the valid values. Based on the given examples, I'd assume that only alphanumericals are accepted. If there is a limit on the length, then you should specify that as well.

Since, you are only looking for values assigned to Material property; no need to store the word Material as a matched-group result.

For eg.

Material=(?<value>[A-Z\d]{6})
answered Jan 10, 2018 at 18:50
\$\endgroup\$
2
  • \$\begingroup\$ I store materialCode into a database so it can't be null. If a value isn't found it has to be "NA". Also there are lots of combos which is why I specify I need whatever value after the = but before the , \$\endgroup\$ Commented Jan 10, 2018 at 19:01
  • 4
    \$\begingroup\$ @Anonguy123 Those specifications/limitations should be mentioned in question. \$\endgroup\$ Commented Jan 10, 2018 at 19:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.