0

What is the correct regex for getting a string that contains only letters, must start with letters and a continuous string of letters. But can end with letters OR a space (just space and not tabs or returns).

I have this pattern /^\S*[a-zA-Z]\s*$/

Is it correct? do I need the \S* at the start and how do I ensure that there is no spaces in between letters?

TIA

tchrist
  • 78,834
  • 30
  • 123
  • 180
Jamex
  • 1,164
  • 5
  • 22
  • 34

4 Answers4

4

if it must start with letters, contain only letters (no spaces), and could end with a single space i think it should be

^[a-zA-Z]+ ?$
jambriz
  • 1,273
  • 1
  • 10
  • 25
  • Thanks jambriz, this works too. My problem now is to investigate which solution is most optimal for getting about 90K matches out of a 200K array. – Jamex Mar 16 '12 at 19:06
2

/^[a-zA-Z]+[a-zA-Z ]$/

No need for \S*

And you can test it online. There are websites such as http://www.solmetra.com/scripts/regex/ to check regex.

RNA
  • 146,987
  • 15
  • 52
  • 70
  • That site looks pretty good. Try http://gskinner.com/RegExr/. It's my regex weapon of choice :). I really like the real-time updating and the replace option. – kentcdodds Mar 16 '12 at 18:27
  • Thanks RNAer, that testing website looks good. It actually is intuitive and I can test my string a see the outputs. Also, I modified your regex to take out the 'space' that comes after the + sign. That mod works for my intent. /^[a-zA-Z]+[a-zA-Z ]$/ – Jamex Mar 16 '12 at 18:58
  • @Jamex:Yes. That space is a typo. It should be removed. Sorry – RNA Mar 17 '12 at 03:16
2

^[a-zA-Z]+?[a-zA-Z ]$

This assumes a modern regular expression processor which allows for non-greedy (+?) repeats.

Lance Helsten
  • 9,457
  • 3
  • 16
  • 16
  • 1
    Thanks Lance, this works for my purpose. But for my purpose, it can also work without the '?' mark. ^[a-zA-Z]+[a-zA-Z ]$ – Jamex Mar 16 '12 at 19:02
1

To be unicode compatible:

^\pL ?$
Toto
  • 89,455
  • 62
  • 89
  • 125
  • Thanks M42 for your time, I am sure this is really useful if I know which context to apply it to. – Jamex Mar 17 '12 at 02:48