0

I am new to regular expressions. I am looking for String which can have only characters 'SALT' which is prefixed by + or – sign.

I am using [(SALT){1}\+-]{8} which is partially working. Not completely.

Total characters 8

Acceptable values

+S+A+L+T

+S-A-L+T

+T+L+A+S

These are the following values which are not acceptable.

No repeat of characters except +,- as a prefix only.

i.e

S+L+S+S ( Character is repeated in this )
S+++++ 
-------S
S-+S-+S

I would appreciate if anyone help me in this regard.

Thanks

6
  • Is this a homework question? Commented Apr 26, 2013 at 20:39
  • 1
    "No repeat of characters" is a difficult requirement for a regex. It usually ends messy. Commented Apr 26, 2013 at 20:40
  • For a start, read the basic syntax manual again.[(SALT)] is a character class; it matches a single character which can be a literal ( or S or A or ... Commented Apr 26, 2013 at 20:43
  • @Dukeling Well if there are only four characters, (s)he could do a negative lookahead / negative lookbehind for each of them. I agree though. Commented Apr 26, 2013 at 20:44
  • There are different regex flavors. If a Perl regular expression is acceptable, it makes this a lot easier (or, at least vaguely possible) than if you are restricted to traditional basic or extended regular expressions. Commented Apr 26, 2013 at 20:46

3 Answers 3

5

You can use lookaheads to make sure all of your characters are there

^(?=.*S)(?=.*A)(?=.*L)(?=.*T)([+-][SALT]){4}$
Sign up to request clarification or add additional context in comments.

4 Comments

... provided your platform's regex support is Perl compatible.
@CasimiretHippolyte why do you say that?
@ExplosionPills Because the first character must be a + or -, but it doesn't make a big difference.
The above answer works for me. thanks for overwhelming response for this question.
0

A funny way (if the RE engine supports conditionnals and backreferences) :

^(?:[+-](?:(S(?(1)Z))|(A(?(2)Z))|(L(?(3)Z))|(T(?(4)Z)))){4}$

Comments

-1

Try this:

^(([+\-]([SALT]))(?!\2))+$

It uses negative lookahead assertion to prevent matching repeating ones.

3 Comments

This will match SSSSSSSSSSSSSSSSSSSSSSSS...
+S+S-S+S-S+S. It won't prevent duplicates.
Still would allow -S-A-A-A.

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.