我正在努力寻找出现在倾斜(~)标志边界内的单词。
e.g. ~albert~ is a ~good~ boy.我知道,通过使用~.+?~,这是可能的,它已经对我起作用了。但在特殊情况下,我需要匹配嵌套的倾斜句。
e.g. ~The ~spectacle~~ was ~broken~在上面的例子中,我必须分别捕捉“眼镜”、“眼镜”和“破碎的”。这些将被逐字翻译或随附文章(An,The,无所谓).原因是在我的系统中:
1) 'The spectacle' requires a separate translation on a specific cases.
2) 'Spectacle' also needs translation on specific cases.
3) IF a tranlsation exist for The spectacle, we will use that, ELSE
we will use 另一个解释这一点的例子是:
~The ~spectacle~~ was ~borken~, but that was not the same ~spectacle~
that was given to ~me~.在上面的例子中,我将翻译如下:
1) 'The spectacle' (because the translation case exists for 'The spectacle', otherwise I would've only translated spectacle on it's own)
2) 'broken'
3) 'spectacle'
4) me我在组合一个表达式时遇到了问题,该表达式将确保在我的正则表达式中捕获到这个表达式。到目前为止,我设法与之合作的是‘~+?~’。但我知道,通过某种形式的向前看或放眼看,我可以做到这一点。有人能帮我吗?
这其中最重要的方面是防回归,这将确保现有的东西不会损坏。如果我能把它做好,我就把它发出去。
注:如果有帮助的话,目前我只会有一个嵌套级别需要分解的实例。所以~奇观~~将是最深的层次(直到我需要更多!)
发布于 2015-05-22 14:35:06
我以前写过这样的东西,但是我还没有对它进行太多的测试:
(~(?(?=.*?~~.*?~).*?~.*?~.*?~|[^~]+?~))或
(~(?(?=.*?~[A-Za-z]*?~.*?~).*?~.*?~.*?~|[^~]+?~))另一种选择
(~(?:.*?~.*?~){0,2}.*?~)
^^ change to max depth最有效的方法
要添加更多内容,请在两处添加一些额外的.*?~集。
主要问题
如果我们允许无限的嵌套,我们怎么知道它会在哪里结束和开始?笨拙的图表:
~This text could be nested ~ so could this~ and this~ this ~Also this~
| | |_________| | |
| |_______________________________| |
|____________________________________________________________________|或者:
~This text could be nested ~ so could this~ and this~ this ~Also this~
| | | | |_________|
| |______________| |
|___________________________________________________|编译器将不知道选择哪一个。
为你的判决
~The ~spectacle~~ was ~broken~, but that was not the same ~spectacle~ that was given to ~me~.
| | ||_____| | | |
| | |_____________| | |
| |____________________________________________________| |
|___________________________________________________________________|或者:
~The ~spectacle~~ was ~broken~, but that was not the same ~spectacle~ that was given to ~me~.
| |_________|| |______| |_________| |__|
|_______________|我该怎么办?
使用交替字符(如@tbraun建议的那样),以便编译器知道从何处开始和结束:
{This text can be {properly {nested}} without problems} because {the compiler {can {see {the}}} start and end points} easily. Or use a compiler:注意:我不经常使用Java,所以有些代码可能不正确
import java.util.List;
String[] chars = myString.split('');
int depth = 0;
int lastMath = 0;
List<String> results = new ArrayList<String>();
for (int i = 0; i < chars.length; i += 1) {
if (chars[i] === '{') {
depth += 1;
if (depth === 1) {
lastIndex = i;
}
}
if (chars[i] === '}') {
depth -= 1;
if (depth === 0) {
results.add(StringUtils.join(Arrays.copyOfRange(chars, lastIndex, i + 1), ''));
}
if (depth < 0) {
// Balancing problem Handle an error
}
}
}这使用StringUtils
发布于 2015-05-22 15:59:58
您需要一些东西来区分开始/完成模式。即{}
不能使用模式\{[^{]*?\}排除{。
{The {spectacle}} was {broken}第一次迭代
{spectacle}
{broken}第二次迭代
{The spectacle}https://stackoverflow.com/questions/30393843
复制相似问题