Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading