如何在正则表达式中替换前瞻? [英] How to replace lookahead in regex?

查看:71
本文介绍了如何在正则表达式中替换前瞻?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个正则表达式来验证输入字符串.它的最小长度必须为8个字符(由字母数字和标点字符组成),并且必须至少具有一个数字和一个字母字符.所以我想出了正则表达式:

I wrote a regex that validates an input string. It must have a minimum length of 8 chars (composed by alphanumeric and punctuation chars) and it must have at least one digit and one alphabetic char. So I've come up with the regex:

^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9-,._;:]{8,}$

现在我必须使用不支持先行的语言来重写此正则表达式,我该如何重写该正则表达式?

Now I have to rewrite this regex in a language that doesn't support lookahead, how should I rewrite that regex?

有效输入为:

1foo,bar
foo,bar1
1fooobar
foooobar1
fooo11bar
1234x567
a1234567

无效输入:

fooo,bar
1234-567
.1234567

推荐答案

有两种方法.一种是编写一个可处理所有可能替代方案的表达式:

There are two approaches. One is to compose a single expression which handles all possible alternatives:

^[a-zA-Z][0-9][a-zA-Z0-9-,._;:]{6,}$
  |
^[a-zA-Z][a-zA-Z0-9-,._;:][0-9][a-zA-Z0-9-,._;:]{5,}$
  |
^[a-zA-Z][a-zA-Z0-9-,._;:]{2}[0-9][a-zA-Z0-9-,._;:]{4,}$

等这是一个组合梦comb,但它可以正常工作.

etc. This is a combinatoric nightmare, but it would work.

一种更简单的方法是使用两个表达式两次验证同一字符串:

A much simpler approach is to validate the same string twice using two expressions:

^[a-zA-Z0-9-,._;:]{8,}$          # check length and permitted characters

[a-zA-Z].*[0-9]|[0-9].*[a-zA-Z]  # check required characters

@briandfoy正确地指出,分别搜索每个必需字符将更有效:

@briandfoy correctly points out that it will be more efficient to search for each required character separately:

[a-zA-Z]                         # check for required alpha

[0-9]                            # check for required digit

这篇关于如何在正则表达式中替换前瞻?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆