Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exclude a certain double character in a regex

Tags:

regex

I'm having trouble wrapping my head around a regex.

so far my pattern looks like this ( Python Verbose flavor regex )

(?P<text>
 [a-zA-Z0-9]+        # can start with "core char"
 [a-zA-Z0-9\ \-]*     # can have a "core char" or space|dash within it
 [a-zA-Z0-9]+        # must end with a "core character"
)

I want to change this so within that middle section, I don't match on have a repeating space or dash. Having multiple spaces/dashes within the text is acceptable.

good:

hello world
hello-world
h-ll-w-rld

bad:

-hello-world
hello--world
h-ll--w-rld
hello  world
like image 834
Jonathan Vanasco Avatar asked Sep 07 '25 05:09

Jonathan Vanasco


2 Answers

Try this:

(?P<text>
 [a-zA-Z0-9]+
 ([ -][a-zA-Z0-9]+)*
)
like image 129
ctn Avatar answered Sep 10 '25 06:09

ctn


You can have something like the following:

^([a-zA-Z0-9]+[\ \-]?)*[a-zA-Z0-9]+$

http://rubular.com/r/VGfGTrqayR


If you ALWAYS want to have 2 or more words, than you'd use the following instead

^([a-zA-Z0-9]+[\ \-])+[a-zA-Z0-9]+$

http://rubular.com/r/EdV3iBQbsw

like image 43
Sam I am says Reinstate Monica Avatar answered Sep 10 '25 05:09

Sam I am says Reinstate Monica