How to construct the regular expression for the case?

Asked

Viewed 209 times

2

I need to create an expression for the following case of a code field:

  • No maximum number of characters
  • The first digit should only be numbers [0-9]
  • The code is composed of alphanumeric digits and only the characters / (bar) and - (hyphen), and not always have all of them.

I tried to start one, but without success:

^[0-9][a-zA-Z0-9\/-]+$

Example of results

valid:

260509
8605/05
5ABC605/05
756574-7
88BS-AS0

Invalid:

A8605/05
B756574-7
  • What problem are you having Marcelo? I tested your regex and it worked, of course it can be improved but you reported that it had not worked and when testing it all worked.

1 answer

3


I believe this regex serves to capture the desired pattern:

^\d([\w\-/]*)

It means, the first character must be a number, followed by a group containing a list of caracateres a-za-Z0-9_-/

  • 1

    a bar was missing before the /, d([ w-/]*)

  • @Erickgallani I tested in Notepad++ and as no language was specified I did not escape this :P bar, depending on the language is accurate yes as you said.

  • 1

    if the hyphen is the last character of the class it does not need to be escaped: ^\d([\w/-]*)

  • At least in online testing, only captured the first value 260509, @rray

  • 1

    @Marcelodeandrade are you trying to use javascript this regex? If yes you need to do the following / d([ w-/]*)/gm (g = of global and m = multilines)

  • @Marcelodeandrade has the link p test? which language you used?

  • @Sanction did not know this, was worth the tip :)

  • @rray a yes, depending on the language does not really need is that I always end up testing on https://regex101.com/ which uses javascript as standard kkk

  • @Marcelodeandrade see the example working https://regex101.com/r/aV7fV5/1

  • 1

    Yes and something else @Erickgallani called g and the m global matching and multi-line matching.

  • Here ó: https://regex101.com/r/kP8tL9/1

  • Now it worked after calling g and m.

  • In javascript, as would regex so that if you do not match the input, it is incorrect?

  • @Marcelodeandrade, it’s called: input.match(/^\d([\w\/-]*)/g) and plays on an if, it will return a boolean.

  • Thanks, @rray. I expressed myself erroneously, what I would need is this inverted match. The control is directly in the input: this.value=this.value.replace(/^\d([\w\/-]*)/g,'')

  • @Marcelodeandrade, confused everything haha did not understand anything, could explain again :)

  • Fez another issue detailing.

Show 12 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.