1

I have three different things

xxx xxx>xxx xxx>xxx>xxx 

Where xxx can be any combination of letters and number

I need a regex that can match the first two but NOT the third.

3
  • Are these three different "things" all that there is in the string, or are you trying to find those in a larger string? Commented Apr 24, 2012 at 14:50
  • Do you only want to match the xxxs or also the >? In other words, are you trying to extract the xxxs? Commented Apr 24, 2012 at 14:54
  • How is this question different from this one: stackoverflow.com/questions/8854363/… ... aside from the number of characters you want to match. Commented Apr 24, 2012 at 15:13

2 Answers 2

5

To match ASCII letters and digits try the following:

^[a-zA-Z0-9]{3}(>[a-zA-Z0-9]{3})?$ 

If letters and digits outside of the ASCII character set are required then the following should suffice:

^[^\W_]{3}(>[^\W_]{3})?$ 
Sign up to request clarification or add additional context in comments.

2 Comments

Note that this pattern assumes that the string occupies a whole line. Otherwise, omit the ^ and/or $, but hen you have to exclude a possible > after the second letters group.
This only matches ASCII letters and digits.
1
^\w+(?:>\w+)?$ 

matches an entire string.

\w+(?:>\w+)?\b(?!>) 

matches strings like this in a larger substring.

If you want to exclude the underscore from matching, you can use [\p{L]\p{N}] instead (if your regex engine knows Unicode), or [^\W_] if it doesn't, as a substitute for \w.

3 Comments

\w also matches _ in addition to [A-Za-z0-9].
That won't match the first entry.
@djechlin: True, but then ä is a letter, too, and [a-z] won't match that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.