【问题标题】:Regex pattern to match any substring longer than two characters from a provided string正则表达式模式匹配提供的字符串中超过两个字符的任何子字符串
【发布时间】:2016-03-24 19:30:53
【问题描述】:

我有一个输入字符串,比如说potato。我在 Visual Studio 中有一个大型项目。我正在尝试编写一个正则表达式来查找输入的任何长于两个字符的子字符串。比如potatotat等。

/([p,o,t,a]){2,10}/g

这会查找包含这些字母的长度介于 2 到 10 个字符之间的任何字符串,但不考虑顺序。我希望有效地做

/([potato]){2,10}/g

并让它只返回在提供的字符串中找到的子字符串。这甚至可能吗?

【问题讨论】:

  • 首先,如果您正在搜索子字符串,那么最大长度应该是该字符串的长度。在这种情况下 6.
  • 也许通过递归,例如如果它与 s[i] 匹配,则使用 s[i+1] 调用?
  • 输入的来源是什么?用户?它在哪里寻找用户输入字符串的子字符串?
  • @noob,很好。我的实际输入字符串是 10 个字符,我只是忘记为问题更新它。输入的来源是用户。这是我在 Visual Studio 的搜索框中输入的内容
  • @DavidBrossard 看到我只是在 Visual Studio 中使用搜索框,我不知道如何递归

标签: regex string visual-studio-2015


【解决方案1】:

对于给定的例子,这个正则表达式可以完成这项工作:

(((pota?|ota)t?|tat)o?|ato)

这采用嵌套 OR (|) 表达式中所有可能的 3 字符子字符串,并匹配所有后续字符(如果它们存在)(可选)。

此表达式中有一个可重复的逻辑,因此它可以从任何用户提供的搜索项动态构建。

为了证明这一点,这里有一个实时的 JavaScript sn-p 可以做到这一点。它允许您输入搜索字符串和要搜索的文本。然后它输出正则表达式并应用它,突出显示匹配的文本部分。

将其翻译成任何其他支持正则表达式的语言都很简单:

// Core function
function buildRegexFor(find) {
    var regexStr = find.substr(0,3);
    for (var i = 1; i < find.length - 2; i++) {
        regexStr = '(' + regexStr + find.substr(i+2,1) + '?|' + find.substr(i,3) + ')';
    }
    return regexStr;
}

// Handle button click event 
document.querySelector('button').onclick = function () {
    // (1) read input
    var find = document.querySelector('input').value;
    var str = document.querySelector('textarea').value;

    // (2) build regular expression using above function
    var regexStr = buildRegexFor(find);
    
    // (3) apply regular expression to text and highlight all found instances   
    str = str.replace(new RegExp(regexStr, 'g'), "<b>$1</b>");
    
    // (4) output
    document.querySelector('span').textContent = regexStr;
    document.querySelector('div').innerHTML = str;
};
b { background: yellow }
Value to find:<br>
<input value="potato"><br>
<button>find</button><br>
Text to find in:<br>
<textarea cols=40>There is a spot in the botanic garden 
on this atol that beats all stats as it rotates potatoes.</textarea><br>
Regex: <span></span><br>
<div></div>

【讨论】:

  • 这回答了您的问题吗?你能发表评论吗?
【解决方案2】:

您可以通过编程方式生成字符串(Python 中的示例):

s = "potato"
min_length = 3

substrings = set()
for x in range(len(s)):
    for y in range(x + min_length, len(s)):
        substrings.add(s[x:y])

pattern = "(" + "|".join(substrings) + ")"
print(pattern)

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多