EN VI

Regex to match N chars followed by another?

2024-03-15 20:30:05
How to Regex to match N chars followed by another

I need a regex to match the largest string (inside a string) with at most 5 chars but the last char has to be an X letter.

For example, I want the strings below to be converted to:

abXdef -> abX
abcdX-> abcdX
aXcdXf-> aXcdX

I am using PHP (but you can use any other language, no problem) and so far I came up with this:

preg_replace("/^(.{4})X.+$/","$1","abcdXef");

But it only works if the X is exactly at the fifth position. Any idea how I can fix this?

Solution:

Using regex101 i came up with this

[a-zA-Z]{1,5}[xX]

I made an edit to also get Uppercase letters

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login