Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are some built-in functions that can clean up your code. And I think you're not leveraging the full power of regular expressions.</p> <p>The blaring issue here is <code>strsplit</code>. Comparing the equality of things character-by-character is inefficient when you have regular expressions. The pattern here uses the square bracket notation to filter for the characters you want. <code>*</code> is for any number of repeats (including zero), while the <code>^</code> and <code>$</code> symbols represent the beginning and end of the line so that there is nothing else there. <code>nchar(word)</code> is the same as <code>length(chars)</code>. Changing <code>&amp;&amp;</code> to <code>&amp;</code> makes the function vectorized so you can input a vector of strings and get a logical vector as output.</p> <pre><code>check.pattern.2 = function(word, min.size = 2) { word = trim(word) grepl(paste0("^[a-z!.?]*$"),word) &amp; nchar(word) &gt;= min.size } check.pattern.2(c(" d ","!hello ","nA!"," asdf.!"," d d ")) #[1] FALSE TRUE FALSE TRUE FALSE </code></pre> <p>Next, using curly braces for number of repetitions and some <code>paste0</code>, the pattern can use your min.size:</p> <pre><code>check.pattern.3 = function(word, min.size = 2) { word = trim(word) grepl(paste0("^[a-z!.?]{",min.size,",}$"),word) } check.pattern.3(c(" d ","!hello ","nA!"," asdf.!"," d d ")) #[1] FALSE TRUE FALSE TRUE FALSE </code></pre> <p>Finally, you can internalize the regex from <code>trim</code>:</p> <pre><code>check.pattern.4 = function(word, min.size = 2) { grepl(paste0("^\\s*[a-z!.?]{",min.size,",}\\s*$"),word) } check.pattern.4(c(" d ","!hello ","nA!"," asdf.!"," d d ")) #[1] FALSE TRUE FALSE TRUE FALSE </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload