Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match any combination of letters using regex?

How can I match letters a,b,c once in any combination and varying length like this:

The expression should match these cases:

abc
bc
a
b
bca

but should not match these ones:

abz
aab
cc
x
like image 312
John_Sheares Avatar asked Nov 24 '12 22:11

John_Sheares


People also ask

How do you match a character sequence in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is the regex for any character?

Matching a Single Character Using Regex By default, the '. ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.

What regex will find letters between two numbers?

To solve my problem I just tried this regex: "\d{1}[A-Z]{1}\d{1}" but it extract 9A1 or 9C1 given examples strings here above. You should be able to use a capture group to extract the letter you need.

Which regular expression matches any character except X Y Z?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).


2 Answers

Use regex pattern

\b(?!\w*(\w)\w*\1)[abc]+\b

You can use this pattern with any set and size, just replace [abc] with desired set...


Example:

enter image description here

(above output is from myregextester)

like image 79
Ωmega Avatar answered Oct 03 '22 00:10

Ωmega


^(?=(.*a.*)?$)(?=(.*b.*)?$)(?=(.*c.*)?$)[abc]{,3}$

The anchored look-aheads limit the number of occurrences of each letter to one.

like image 39
Bohemian Avatar answered Oct 03 '22 02:10

Bohemian