2

I need a regular expression that checks if every - in the string has a letter before and after it.

I got this so far:

(([-])?[a-zA-Z ]+[a-zA-Z]+[-]+[a-zA-Z]+[a-zA-Z ]+$|[a-zA-Z ]+$)|([a-zA-Z ])

works for these examples:

  • Tester
  • tester_test
  • Tes ter_te st

It doesn't work for these examples:

  • Tester_test tester_test
  • te st_te_st_te_st

2 Answers2

1

To ensure that every underscore is surrounded by a letter, you can use

(?<=[a-zA-Z])_(?=[a-zA-Z])

Regular expression visualization

Debuggex Demo

This demo works for all of your inputs.

This uses a positive lookbehind ((?<=...)) and lookahead ((?=...)).


Please consider bookmarking the Stack Overflow Regular Expressions FAQ for future reference. There is a section on lookarounds that may be of interest, as well as a list of online testers at the bottom.

Community
  • 1
  • 1
aliteralmind
  • 19,847
  • 17
  • 77
  • 108
  • What does ?<= mean? I don't find anything about this in google. – Xatenev Apr 15 '14 at 12:53
  • @Xatenev: Updated my answer. They're the lookaheads and behinds I mentioned. – aliteralmind Apr 15 '14 at 12:56
  • Uncaught SyntaxError: Invalid regular expression – Lendl Verschoor Apr 15 '14 at 13:32
  • 1
    This is structurally one of the best regex related answers I have seen in a while! Sadly debuggex only supports javascript, python and perl. The ASP.NET syntax might be different and the lookahead feature might not even exist there - I dont know. @eXo the mentioned FAQ is really helpful, go check it out. – SebastianH Apr 15 '14 at 14:01
  • It works for me at regexhero, which is an online tester for .NET regular expressions: http://regexhero.net/tester/?id=35632c5b-ccbd-430b-a8e5-97f833b1b08f. @eXo: Are you going to give us some more information so we can help you better, or are you just going to throw error-messages at us? – aliteralmind Apr 15 '14 at 14:06
1

This regex seemed to work for all your Examples, and aswell as alot of others. Check for the negation of following:

^(.*(([^a-zA-Z]-)|(-[^a-zA-Z])).*)$

Check this regex out here, with a lot of examples:

http://www.rubular.com/r/o2OZYJheIt

Xatenev
  • 6,383
  • 3
  • 18
  • 42