-4

I want to write a regular expression which can extract the number between 0 to 360 in a string. Following are the example:

Text: "Rotate by 360 degrees"
OP: 360

Text: "36 degrees degree rotation"
OP: 36

Text: "rotate 100"
OP: 100

Text: "rotate 6700"
OP: NA (as 6700 is out of range)

I want to achieve it by regular expression

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Shreeti
  • 1
  • 2

2 Answers2

2

Enumerate the possibilities:

\b([0-2]?[0-9]{1,2}|3[0-5][0-9]|360)\b
iBug
  • 35,554
  • 7
  • 89
  • 134
1

#RegEx Number Range [0-9] The \b word boundary meta is to ensure that words like: 36000 or l337 doesn't match. There are 3 character class ranges (hundreds 1-2|3, tens 0-9|0-5, and ones 0-9). The ? is a lazy quantifier because the hundreds and tens aren't necessarily there all the time. The pipe | and surrounding parenthesis are alternations for 360 since the tens cannot be [0-6] because doing so leaves the possibility of matching 361 thru 369.

3[0-5][0-9] /* 300-359 */ |360 // 360

Although the possibility of exceeding 360 is prevented, so is the possibility of getting ranges of 160-199 and 260-299. We can add another alternation: | and change the ranges a little:

[1-2]?[0-9]?[0-9] // 0-299
  • So to recap:

  • \b keeps adjacent characters from bleeding into the matches

  • [...] covers a range or a group of literal matches

  • ? makes the preceding match optional

  • (...|...) is an OR gate

\b([1-2]?[0-9]?[0-9]|3[0-5][0-9]|360)\b

The equivalent for [0-9] as a meta sequence is \d.

Thanks go out to Master Toto for pointing out the range flaws.


##Demo

var str = `
Rotate by 360 degrees
36 degrees rotation
Rotate 100
Turn 3600
Rotate 6700
270Deg
0 origin
Do not exceed 361 degrees or over
Turn 180 degrees back
369 is also 9
00 is not a real number
010 is not a real number either
1, 20, 300, 99, and 45 should match because a comma: "," is a non-word character
`;

var rgx = /\b([1-3]0?[0-9]|[1-2]?[1-9]?[0-9]|3?[1-5]?[0-9]|360)\b/g;

var res = str.match(rgx, '$1');

console.log(JSON.stringify(res));
zer00ne
  • 41,936
  • 6
  • 41
  • 68