Software Engineering

Methods to String Search with a Wildcard in Java

Methods to String Search with a Wildcard in Java
Written by admin


The problem

The tactic beneath is the simplest string search algorithm. It should discover the primary prevalence of a phrase in a textual content string.

haystack = the entire textual content

needle = searchword

wildcard = _

discover("strike", "i'll strike down upon thee"); // return 7

The discover methodology is already made.

The issue is to implement wildcard(s) within the needle. In case you have a _ within the needle it’s going to match any character within the haystack.

A standard string search algorithm will discover the primary prevalence of a phrase(needle) in a textual content(haystack), beginning on index 0. Like this:

discover("strike", "I'll strike down upon thee"); //return 7

A wildcard within the needle will match any character within the haystack. The tactic ought to work on any kind of needle, and haystacks. You’ll be able to assume the needle is shorter than(or equal to) the haystack.

discover("g__d", "That is the benefit of being president"); // return 11

If no match the tactic ought to return -1

The answer in Java code

Possibility 1:

import java.util.regex.*;
public class SearchEngine {
  static int discover(String needle, String haystack){
    String regNeedle = "Q" + needle.replaceAll("_", "\E.\Q") + "E";
    Matcher m = Sample.compile(regNeedle).matcher(haystack);
    if(m.discover()) return m.begin();
    else return -1;
  }
}

Possibility 2:

import java.util.regex.*;
public class SearchEngine {
  static int discover(String needle, String haystack){
    Matcher m = Sample.compile(
        Sample.quote(needle).exchange("_", "E.Q")
      ).matcher(haystack);
    return m.discover() ? m.begin() : -1;
  }
}

Possibility 3:

import static java.util.regex.Sample.compile;
class SearchEngine {
  static int discover(String needle, String haystack) {
    var m = compile("Q" + needle.exchange("_", "E.Q") + "E").matcher(haystack);
    return m.discover() ? m.begin() : -1;
  }
}

Check circumstances to validate our resolution

import org.junit.Check;
import static org.junit.Assert.assertEquals;
public class WildsTest {
    String haystack = "As soon as upon a midnight dreary, whereas I contemplated, weak and weary";    
    @Check
    public void normalSearchTest(){
        assertEquals(0,SearchEngine.discover("As soon as", haystack));
        assertEquals(12, SearchEngine.discover("midnight", haystack));
        assertEquals(-1, SearchEngine.discover("codewars", haystack));
    }
    @Check
    public void wildSearchTest(){
        assertEquals(5, SearchEngine.discover("_po_", haystack));
        assertEquals(12, SearchEngine.discover("___night", haystack));
    }
 }

About the author

admin

Leave a Comment