Wednesday, February 21, 2024
HomeSoftware EngineeringThe right way to String Search with a Wildcard in Java

The right way to String Search with a Wildcard in Java


The problem

The strategy beneath is the simplest string search algorithm. It would 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 technique is already made.

The issue is to implement wildcard(s) within the needle. In case you have a _ within the needle it can 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 strategy ought to work on any kind of needle, and haystacks. You may assume the needle is shorter than(or equal to) the haystack.

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

If no match the tactic ought to return -1

The answer in Java code

Choice 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;
  }
}

Choice 2:

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

Choice 3:

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

Take a look at instances to validate our answer

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments