regex specifying a "max length"

2,381 views
Skip to first unread message

netbrain

unread,
Feb 9, 2013, 2:31:49 PM2/9/13
to golan...@googlegroups.com
in go if you try to match a string against the regex '.{10,20}' then you would get the following result

'test' = no match
'12345678910' = match
'1234567891012345678910' = match

However i was expecting the last to fail. In HTML5, this regex would not match against the last example. 

How can i go about creating a regex or invoking the regex api in such a way that i would get the result i expected?

-Kim

Jan Mercl

unread,
Feb 9, 2013, 2:56:46 PM2/9/13
to netbrain, golang-nuts
On Sat, Feb 9, 2013 at 8:31 PM, netbrain <k...@heldig.org> wrote:
> in go if you try to match a string against the regex '.{10,20}' then you
> would get the following result
>
> 'test' = no match
> '12345678910' = match
> '1234567891012345678910' = match

`.{10,20}$` // not tested (?)

-j

Martin Schnabel

unread,
Feb 9, 2013, 2:59:19 PM2/9/13
to golan...@googlegroups.com
`^.{10,20}$` // tested ;)

http://play.golang.org/p/wshiTxLxWa

Robert Tweed

unread,
Feb 9, 2013, 3:03:20 PM2/9/13
to netbrain, golan...@googlegroups.com
Your understanding of this regex is off, and if it doesn't match the second example in some implementation, then that implementation is broken (or is silently adding rules, which may be true if you're using a pre-baked validation library, for example). Asking for a range like '.{10,20}' just means "match at least 10, or up to 20 characters, at the first point you can" so it should correctly match "12345678910123456789".

If you want to also assert that you expect the *entire*search string to match that pattern then you need to anchor it to the start and the end of the string, i.e. '^.{10,20}$' - which means match the whole search string if and only if it is between 10 and 20 characters long.

Watch out for the single-line and multi line modes too, which changes the meaning of these anchors if your input string contains newlines.

- Robert
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Kim Eik

unread,
Feb 9, 2013, 3:09:14 PM2/9/13
to Robert Tweed, golan...@googlegroups.com
Gah! offcourse.... i must be tired, why the heck did i know think of ^$? oh well. thanks guys.
Reply all
Reply to author
Forward
0 new messages