查找字符串中最短的重复模式

编程入门 行业动态 更新时间:2024-10-18 18:17:36
本文介绍了查找字符串中最短的重复模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道在Octave/matlab中是否可以进行模式匹配?我知道Maple 10有执行此操作的命令,但不确定在Octave/Matlab中我需要做什么.因此,如果数字为12341234123412341234,则模式匹配将为1234.我正在尝试找到最短的模式,该模式在重复时会生成整个字符串.

I was wondering if there was a way to do pattern matching in Octave / matlab? I know Maple 10 has commands to do this but not sure what I need to do in Octave / Matlab. So if a number was 12341234123412341234 the pattern match would be 1234. I'm trying to find the shortest pattern that upon repetiton generates the whole string.

请注意:数字(只会使用数字)不是那么简单.另外,我不会提前知道模式(这就是我要查找的东西).请参阅 枫叶10示例 在下面显示该模式不是预先知道的,但是命令会找到该模式.

Please note: the numbers (only numbers will be used) won't be this simple. Also, I won't know the pattern ahead of time (that's what I'm trying to find). Please see the Maple 10 example below which shows that the pattern isn't known ahead of time but the command finds the pattern.

Maple 10模式匹配示例:

Example of Maple 10 pattern matching:

ns:=convert(12341234123412341234,string); ns := "12341234123412341234" StringTools:-PrimitiveRoot(ns); "1234"

如何在Octave/Matlab中执行此操作? 附:我正在使用Octave 3.8.1

How can I do this in Octave / Matlab? Ps: I'm using Octave 3.8.1

推荐答案

要查找重复生成整个字符串的最短模式,可以使用如下正则表达式:

To find the shortest pattern that upon repetition generates the whole string, you can use regular expressions as follows:

result = regexp(str, '^(.+?)(?=\1*$)', 'match');

一些例子:

>> str = '12341234123412341234'; >> result = regexp(str, '^(.+?)(?=\1*$)', 'match') result = '1234' >> str = '1234123412341234123'; >> result = regexp(str, '^(.+?)(?=\1*$)', 'match') result = '1234123412341234123' >> str = 'lullabylullaby'; >> result = regexp(str, '^(.+?)(?=\1*$)', 'match') result = 'lullaby' >> str = 'lullaby1lullaby2lullaby1lullaby2'; >> result = regexp(str, '^(.+?)(?=\1*$)', 'match') result = 'lullaby1lullaby2'

更多推荐

查找字符串中最短的重复模式

本文发布于:2023-11-30 09:32:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649509.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最短   字符串   模式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!