Get id from a paragraph

For ID 1234 ,matches:4567 requirements 1
467 requirements 2

My output should be:
4567
467 in a datatable.

While using this regex scenario I will get the above output
System.Text.RegularExpression.Regex.Matches(Input variable,“(?<!ID\s+)\b\d{3,}\b”,System.Text.regularexpression.RegexOptions.Multiline).Cast(Of System.Text.RegularExpressionMatches(.Select(Function (X) dt.Rows.Add(X.Tostring().Trim())).CopyToDataTable()

But for some scenarios I will get
For ID 1234 ,matches:requirements 1
requirements 2

There is no id if the above regex is used I am getting error as source contains no datatable

Hi @sruthesanju

Your query is quite confusing could you be more specific.

You can check if Matches has found some results before adding to the datatable:

myMatches =

System.Text.RegularExpressions.Regex.Matches(Input variable,"(?<!ID\s+)\b\d{3,}\b",System.Text.RegularExpressions.RegexOptions.Multiline)

If Activity: myMatches.Cast(Of System.Text.RegularExpressions.Match).Any()
Then:

myMatches.Cast(Of System.Text.RegularExpressions.Match).Select(Function (x) dt.Rows.Add(x.Tostring().Trim())).CopyToDataTable()

Or similar handling it as described here:

UPD1/2… - fixes, import hint added
We would also recommend to add
System.Text.RegularExpressions to the imports (namespaces) then the statements can be more shorten

Hi @sruthesanju If I understood your question correctly, You have a text input that contains IDs and requirements, like this:

  • “For ID 1234 ,matches:4567 requirements 1 467 requirements 2”

You want to extract the numbers following “matches:” and list them in a DataTable, so for the example above, the output should be:

  • 4567
  • 467

You are using a regular expression (regex) to find these numbers, but sometimes the text input might not have an ID and might look like this:

  • “For ID 1234 ,matches1 requirements 2”

In such cases, the regex you used doesn’t find any numbers and you get an error saying “source contains no DataTable.”

Steps to Handle This

  1. Extract Numbers: Your regex pattern (?<!ID\s+)\b\d{3,}\b is designed to find numbers not immediately following “ID”. It looks for sequences of digits that are at least 3 digits long.
  • (?<!ID\s+) ensures that the match is not directly preceded by “ID” followed by spaces.
  • \b\d{3,}\b matches sequences of digits with at least 3 digits.
  1. Handle Cases with No ID: When there is no ID in the input and your regex fails, it returns no matches, leading to an error.

Yes correct if no id getting error

What is the variable type of mymatches

The return of Regex.Matches: MatchCollection

fixed it above - refer to myMatches.Cast(Of Match).Any
Assumption that:
RegexImport

UPD1 - Visualization added

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.