jerry
jerry

Reputation: 3

Match anything that is not a-z or A-Z or & followed by a number

Does anyone know how to make a regex that will match if it contains anything other than normal characters or the & symbol but only IF it is followed by one number?

Basically it shouldn’t match if the word contains normal characters, and/or the & symbol followed by one number

Example of words that should not be matched: &9Hello &1Hey&2You

But it should match if it contains a different symbol, or number(s) without & symbol

Example of words that should be matched: @3Hello 3Hello _Hey5 &12Hello &Hello &1Hello@&£3

Would help me a lot if someone knows how to make a regex for this or explain how I could make it work!

Upvotes: 0

Views: 300

Answers (1)

Slawomir Dziuba
Slawomir Dziuba

Reputation: 1325

You wrote the question not very clearly. If I understand correctly, I give an example in JavaScript.

EDIT:

The following solves the problem assuming that the words 'Hello' and '&1Hello@&£3' have been incorrectly assigned by examples as indicated by the verbal description of the question.

var r=/^((?![A-Za-z&][0-9])|([A-Za-z&][0-9]{2})).*$/;

// not match
console.log(r.test('&9Hello')); 
console.log(r.test('&1Hey&2You')); 

// match
console.log(r.test('@3Hello'));
console.log(r.test('3Hello'));
console.log(r.test('_Hey5'));
console.log(r.test('&12Hello')); 
console.log(r.test('&Hello'));

// Examples given incorrectly
console.log(r.test('&1Hello@&£3'));  // not match
console.log(r.test('Hello'));        // match

EDIT: The answer concerns examples you gave before editing your post.

var r=/^(?![A-Za-z&][0-9]).*$/;
console.log(r.test('3Hello'));
console.log(r.test('&&Hello'));
console.log(r.test('3&Hello'));
console.log(r.test('&3Hello'));

Explanation:

^$ start and end regex
() group elements
?! not containing
[A-Za-z&] one from range characters
[0-9] one from digit
.* any number of any characters

| or
{2} exactly 2

Upvotes: 1

Related Questions