0

I need to create a regular expression that allows a string to optionally contain an asterisk as its first or last character, or both. The string can contain no more than two asterisks and those asterisks must be at the start and/or end of the string.

So these strings would be valid:

foo
*foo
foo*
*foo*

and these strings would not:

*
**
**foo
*f*oo
*f*o*o
*f*o*o*

Thanks in advance.

3
  • What about **, should it match or not? Commented Jul 7, 2011 at 14:44
  • @John: You should restate slightly: "The string can contain no more than two asterisk" is a necessary but not sufficient condition; based on your test cases, it appears that what you mean is that there can not be any asterisks in any other positions besides the first and the last. Commented Jul 7, 2011 at 14:47
  • Good catch. I've edited the question to clarify. Commented Jul 7, 2011 at 14:49

1 Answer 1

10

This should do what you're asking

^\\*?[^*]+\\*?$

Image

Sign up to request clarification or add additional context in comments.

8 Comments

+1, but you can drop the backslashes inside the character class.
@Tim: No, the caret ^ negates the \\* part, which is *. So, [^\\*] means everything except *. Or am I wrong???
@Johan: I saw it was an image, but it looks very nice. Automatically generated is the smell I smell.
@Tim @Martijn: Is it so that regex characters don't need escaping inside a character class? I suppose that would make sense, never noticed though.
@Jason, regular html page + screenshot .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.