I need to create a regex to match all occurrences of a single or double digit (surrounded with a space on each side of the digit). I am trying with this regex:
\s\d{1,2}\s
and I am running it on this string:
charge to at10d to and you 12 sdf 90 fdsf fsdf32 frere89 32fdsfdsf ball for 1 8 toyota
matches:
' 12 ', ' 90 ', ' 1 '
but it does not match the 8 when it is beside the 1. Does anyone know how I can adjust the regex so I can include both these digits together?
I need to create a regex to match all occurrences of a single or double digit (surrounded with a space on each side of the digit). I am trying with this regex:
\s\d{1,2}\s
and I am running it on this string:
charge to at10d to and you 12 sdf 90 fdsf fsdf32 frere89 32fdsfdsf ball for 1 8 toyota
matches:
' 12 ', ' 90 ', ' 1 '
but it does not match the 8 when it is beside the 1. Does anyone know how I can adjust the regex so I can include both these digits together?
Share Improve this question edited Nov 25, 2017 at 16:24 Wiktor Stribiżew 628k41 gold badges498 silver badges614 bronze badges asked Nov 25, 2017 at 16:03 JacksonJackson 3,5282 gold badges20 silver badges29 bronze badges2 Answers
Reset to default 5You are trying the match both the leading and trailing space around the required number. If you just get away with one of these spaces(by using a lookahead as shown below to remove the trailing space), you will get rid of the problem.
Try this regex:
\s\d{1,2}(?=\s)
Explanation:
\s
- matches a white-space\d{1,2}
- matches a 1 or 2 digit number(?=\s)
- returns the position(0-length match) which is followed by a space. So, it doesn't actually matches the space but makes sure that current position is followed by a space
Click for Demo
You can use the word boundry \b
expression.
The word boundary will find numbers that are not wrapped by a letters, numbers or the underscore sign. It will catch 1 or 2 digits that are wrapped by spaces, start and end of string, and non word characters (#12@ - will get he 12).
var str = "51 charge to at10d to and you 12 sdf 90 fdsf fsdf32 frere89 32fdsfdsf ball for 1 8 toyota 12";
var result = str.match(/\b\d{1,2}\b/g);
console.log(result);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744244140a4564845.html
评论列表(0条)