MATLAB Answers

0

regexp to capture only certain length of characters

Asked by Rashmil Dahanayake on 7 Aug 2014
Latest activity Commented on by Azzi Abdelmalek
on 7 Aug 2014
Hi, I'm trying to capture words with 4 characters only. A word consists or alphanumeric characters.(no symbols of white space)
str4='4-44g 4541 75872 a4cd stuvw';
patt4='(\w{4,4})';
regexp(str4,patt4,'match')
I'm expecting 4541 a4cd as the correct answer. However my code outputs stuv & 7587 in addition. How can I correct this

  0 Comments

Sign in to comment.

Tags

Products

2 Answers

Answer by Rashmil Dahanayake on 7 Aug 2014

This could be the solution
str4='4-44g 4541 75872 abcd stuvw';
patt4='\<\w{4}\>';
regexp(str4,patt4,'match')

  1 Comment

This doesn't work for underscore. For example
str4='4-44g 454_ 75872 abcd stuvw'

Sign in to comment.


Answer by Azzi Abdelmalek
on 7 Aug 2014

str4='4-44g 4541 75872 a4cd stuvw';
regexpi([' ' str4 ' '],'(?<=[^0-9,a-z])[0-9,a-z]{4}(?=[^0-9,a-z])','match')

  0 Comments

Sign in to comment.