Understanding compiled regex in .net

I have a regex that will be reused where stringLiteral will differ from one call to another.

One of them:

.*(^stringLiteral Number 1\r?\n)([\w|\s][^\r\n]+)(.+)

and the following:

.*(^stringLiteral Number 2\r?\n)([\w|\s][^\r\n]+)(.+)

Is there any opportunity for optimization here?

EDIT: To be more explicit regarding the live data I work with, I parsed the body of an email containing name / value pairs. I know the names (labels), and I know that the value I after is the line following the label. But I cannot be sure that the name / value pairs (strings) will always be in the same order - therefore I cannot build one big expression.

I need to create several expressions, drop everything from the beginning of the block to and include the given label (this will be stringLiteral); capture the next line in the capture group; then drop everything that follows this line.

so that this string captures the Name field

myOrder.Name = Regex.Replace(resultString, @".*(^Name\r\n)([\w|\s][^\r\n]+)(.+)", "$2", RegexOptions.Multiline | RegexOptions.Singleline);

and this line captures the price field

myOrder.Price= Regex.Replace(resultString, @".*(^Price\r\n)([\w|\s][^\r\n]+)(.+)", "$2", RegexOptions.Multiline | RegexOptions.Singleline);
+3
source share
2 answers

Well, you can condense them into one expression if you want:

.(^stringLiteral Number [12]\r?\n)([\w|\s][^\r\n]+)(.+)

If you post an input example that you want to combine or capture, I could probably help some more.

+2
source

You can condense them into one expression suggested by Andrew.

You should also disable rollback if you don't need it, for example: (?: Subregexp) instead of (subregexp). It saves memory.

0
source

All Articles