Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Regular Expression issue

buntha Choudhary
Ranch Hand
Posts: 136
I am trying to write a regular expression for a scenario where -
user can enter a string containing only a-z or A-Z and may end with a single .

The following are Words :
"ab", "ab."

The following are not Words :
"ab..", "a.b", ".ab", "a.b.", "a2b.", "."

I wrote^([a-zA-Z]\\w(\\D+|\\.))\$ but it is failing with the scenario of . in the mid.

Campbell Ritchie
Sheriff
Posts: 50702
83
Why have you got \\w and \\D in that regular expression?

Campbell Ritchie
Sheriff
Posts: 50702
83

buntha Choudhary
Ranch Hand
Posts: 136
I am very new to Regular Expression.

From the scenario mentioned, there should not be any digit , so I appened \D.
Counting of letters is not required.

Campbell Ritchie
Sheriff
Posts: 50702
83
And \\D will find the . which isn't a digit.

buntha Choudhary
Ranch Hand
Posts: 136
Oh, I got the flaw.
But I've some doubts-

A dot(.) can be provided in the end of the String but not in the mid. So I needed to provide some check for that . How can I do that.
A digit is not comfortable anywhere in the String, so how should be my pattern.

Raymond Tong
Ranch Hand
Posts: 255
2
buntha Choudhary wrote:Oh, I got the flaw.
But I've some doubts-

A dot(.) can be provided in the end of the String but not in the mid. So I needed to provide some check for that . How can I do that.
A digit is not comfortable anywhere in the String, so how should be my pattern.

1) If you specify the pattern to be a-z or A-Z, it can't be digit anyway.
The occurrence of this pattern exists 1 or more times.

2) 1 dot after that

And that's it.

buntha Choudhary
Ranch Hand
Posts: 136
But I am not mandating the dot in the end. We can or can not provide the dot in the end.

Raymond Tong
Ranch Hand
Posts: 255
2
buntha Choudhary wrote:But I am not mandating the dot in the end. We can or can not provide the dot in the end.

Sorry, misread it, the dot with 0 or 1 time.

Rob Spoor
Sheriff
Posts: 20709
68
This shouldn't be too hard:
- [a-zA-Z] one or more times
- a dot zero or one times

buntha Choudhary
Ranch Hand
Posts: 136
Thanks to all.

The pattern I got - ^([a-zA-Z]+\\.{0,1})\$

Campbell Ritchie
Sheriff
Posts: 50702
83
There is a simpler way to do it than {0,1}

buntha Choudhary
Ranch Hand
Posts: 136
@Campbell
Can you please suggest me some more optimistic solution.

Raymond Tong
Ranch Hand
Posts: 255
2