Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expressions, allow specific format only. "John-doe"

Tags:

regex

php

I've researched a little, but I found nothing that relates exactly to what I need and whenever tried to create the expression it is always a little off from what I require.

I attempted something along the lines of [AZaz09]{3,8}\-[AZaz09]{3,8}.

I want the valid result to only allow text-text, where either or the text can be alphabetical or numeric however the only symbol allowed is - and that is in between the two texts.

Each text must be at least three characters long ({3,8}?), then separated by the -.

Therefore for it to be valid some examples could be:

Text-Text
Abc-123
123-Abc
A2C-def4gk

Invalid tests could be:

Ab-3
Abc!-ajr4
a-bc3-25aj
a?c-b%
like image 591
mhvvzmak1 Avatar asked Feb 27 '16 17:02

mhvvzmak1


People also ask

What does \+ mean in regex?

In posix-ere and other regex flavors, outside a character class ( [...] ), + acts as a quantifier meaning "one or more, but as many as possible, occurrences of the quantified pattern*. E.g. in javascript, s. replace(/\++/g, '-') will replace a string like ++++ with a single - .

What are different types of regular expression?

There are also two types of regular expressions: the "Basic" regular expression, and the "extended" regular expression. A few utilities like awk and egrep use the extended expression. Most use the "basic" regular expression. From now on, if I talk about a "regular expression," it describes a feature in both types.

Does regex only work on strings?

So, yes, regular expressions really only apply to strings. If you want a more complicated FSM, then it's possible to write one, but not using your local regex engine.

What is the regular expression?

A Regular Expression (or Regex) is a pattern (or filter) that describes a set of strings that matches the pattern. In other words, a regex accepts a certain set of strings and rejects the rest.


1 Answers

You need to use anchors and use the - so the characters in the character class are read as a range, not the individual characters.

Try:

^[A-Za-z0-9]{3,8}-[A-Za-z0-9]{3,8}$

Demo: https://regex101.com/r/xH3oM8/1

You also could simplify it a but with the i modifier and the \d meta character.

(?i)^[a-z\d]{3,8}-[a-z\d]{3,8}$
like image 61
chris85 Avatar answered Oct 16 '22 12:10

chris85