Author Topic: algorithm to quickly find a pattern in a block  (Read 5166 times)

0 Members and 2 Guests are viewing this topic.

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17773
  • Country: fr
Re: algorithm to quickly find a pattern in a block
« Reply #25 on: February 17, 2025, 12:11:16 pm »
Note that Boyer-Moore can be more efficient than KMP but its worst case complexity is much worse. So if you are dealing with long patterns that are not very likely to repeat (contrary to letter patterns in text), I think I would personally favor KMP.

That said, the complexity of either may be significantly different when introducing wildcards. I haven't thought about it in details. I've implemented both wildcard match and KMP, but never both combined.
 
The following users thanked this post: DiTBho

Offline DiTBhoTopic starter

  • Super Contributor
  • ***
  • Posts: 5083
  • Country: gb
Re: algorithm to quickly find a pattern in a block
« Reply #26 on: February 17, 2025, 01:59:43 pm »
I haven't thought about it in details. I've implemented both wildcard match and KMP, but never both combined.

how did you implemented wildcards?
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17773
  • Country: fr
Re: algorithm to quickly find a pattern in a block
« Reply #27 on: February 18, 2025, 05:53:56 am »
I'll give you the base version, which I think is pretty much the common way of implementing it efficiently. It handles patterns that contain '?' and '*', with the usual definitions for both wildcards. This version is for zero-terminated strings, but it's easy to modify it for arrays of bytes associated with a length. Returns true if the string matches the pattern, false otherwise.

Code: [Select]
bool PatternMatch(const char *szText, const char *szPattern)
{
if ((szText == NULL) || (szPattern == NULL))
return false;

if (*szPattern == '\0')
return (*szText == '\0');

const char *pText = NULL, *pPattern = NULL;

while (*szText != '\0')
{
if ((*szText == *szPattern) || (*szPattern == '?'))
{
szText++;
szPattern++;
}
else if (*szPattern == '*')
{
pText = szText;
pPattern = szPattern;
szPattern++;
}
else if (pPattern != NULL)
{
szText = pText + 1;
szPattern = pPattern + 1;
pText++;
}
else
{
return false;
}
}

while (*szPattern == '*')
szPattern++;

return (*szPattern == '\0');
}
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf