Regex in if statement

Dear everyone

I am pondering if it is possible, given a string and using Regex, to search that string for a certain pattern, if it exist do A if not do B, here is what I am thinking…

Given this textfile made into an array, textArr, where each newline is a new entry in the array:
02318480CVR
1199782489CPR
1235811771CPR
99926118CVR
33221264CVR

I have an if statement that’s inside a for each loop, where I want to do something like this

“If CVR exist in textArr(currentitem) then output textArr(currentitem) in column A else output textArr(currentitem) in column B”.

You may assume I know how to write to a column and you may also assume that the array to correctly set up. All I need to know is what to write in the “if” statement? Any help will be gladely appreciated.

Yours Sincerely…
Bonaparte

Hi @nmjvk

Try this

For Each item In textArr
    If System.Text.RegularExpressions.Regex.IsMatch(item, "CVR") Then
        ' If "CVR" exists in the current item
    Else
        ' If "CVR" does not exist in the current item
    End If
Next

Regards,

1 Like

Dear @lrtetala

That’s it, it works perfect! Can I also ask one small question. What if I want to write the string but WITHOUT the “CVR” or “CPR” at the end? Assume the samme array of strings:
02318480CVR
1199782489CPR
1235811771CPR
99926118CVR
33221264CVR

And since we have the if statement, is it possible to say System.Text.RegularExpressions.RegEx.IsMatch(textFileArray(currentitem),“CPR”) to also use a write cell in excel and do something like “WRITE STRING WITHOUT CPR”?

Kindest regards…
Bonaparte

@nmjvk

If  System.Text.RegularExpressions.Regex.IsMatch(item.ToString(), "CVR|CPR")  Then
     modifiedString = System.Text.RegularExpressions.Regex.Replace(item.ToString(), "(CVR|CPR)", "")
Else

Dear @lrtetala

Thank you very much, that works very well. I will mark your first comment to my actual solution. Have a wonderful day/ night forward!

Kindest regards…
Bonaparte

1 Like

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