Home > other >  Regular expression for word compare
Regular expression for word compare

Time:10-20

I need to regexp for example: compare

c co comp compa compare

I know that i can write like this (c|co|com|comp|compa|compar....), but i have many such word.

I will be glad of any help.

CodePudding user response:

Regex is inefficient for such a task. If you are using some kind of programming language, you can slice the keyword by the length of the test string and test if the sliced string is the same as the test string:

With Python, for example:

def partial_match(keyword, test_string):
    return keyword[:len(test_string)] == test_string
    # or simply,
    # return keyword.startswith(test_string)

# partial_match('compare', 'com') returns True

CodePudding user response:

You can create your patterns with a programming language. In Python:

def create_pattern(s: str):
    return "("   "|".join(s[:i] for i in range(1, len(s)   1))   ")"

print(create_pattern("compare"))

output:

(c|co|com|comp|compa|compar|compare)
  • Related