Search code examples
rowwolfram-mathematicastring-search

Specify Column and Row of a String Search


Because I'm working with a very complex table with nasty repeated values in variable places, I'd like to do a string search between specific rows and columns.

For example:

table={{"header1", "header2", "header3", 
 "header4"}, {"falsepositive", "falsepositive", "name1", 
 "falsepositive"}, {"falsepositive", "falsepositive", "name2", 
 "falsepositive"}, {"falsepositive", "falsepositive", 
 "falsepositive", "falsepositive"}}

%//TableForm=
 header1          header1          header1          header1
 falsepositive    falsepositive    name1            falsepositive
 falsepositive    falsepositive    name2            falsepositive
 falsepositive    falsepositive    falsepositive    falsepositive

How do I look for a string, for example, in column three, rows one through two?

I'd like to use Which to assign values based on a string's location in the table.

E.g.,

Which[string matched in location one, value, matched in location two, value2]

Solution

  • As I understand it you want a test whether or not a given string is in a certain subsection of a matrix. You can pick these subsections using Part ([[...]]) and Span (;;), with which you can indicate ranges or subsamples of ranges. Testing whether or not this subsection contains your pattern can be done by MemberQ, like this:

     MemberQ[table[[1 ;; 2, 3]], "name2"]
    
     (* ==> False *)
    
     MemberQ[table[[1 ;; 2, 3]], "header3"]
    
    (* ==> True *)
    

    In this way, your Which statement could look like this:

    myVar =
     Which[
      MemberQ[table[[1 ;; 2, 3]], "name2"], 5,
      MemberQ[table[[2 ;; 3, 4]], "falsepositive"], 6,
        ...
       True, 20
      ]