I have a string like this:
const string = 'We have this 8/8 / 69 structure in the text/another text and we want to grab it'
and I want to return the part of text which are numbers between slashes. the structure I want is this:
' 8 /8 / 69 '
Number/Number/Number
Note that it could be untrimed:
' 8/ 8 / 69 '
or
'8/8/69'
I tried to split the string by /
and return the structure but the issue is I want to be sure that only the Number/Number/Number
returns.
I have a string like this:
const string = 'We have this 8/8 / 69 structure in the text/another text and we want to grab it'
and I want to return the part of text which are numbers between slashes. the structure I want is this:
' 8 /8 / 69 '
Number/Number/Number
Note that it could be untrimed:
' 8/ 8 / 69 '
or
'8/8/69'
I tried to split the string by /
and return the structure but the issue is I want to be sure that only the Number/Number/Number
returns.
1 Answer
Reset to default 2You can use a simple /[0-9]+ *\/ *[0-9]+ *\/ *[0-9]+/
regex:
[0-9]+
: 1 or more digits*
: any number of spaces\/
: a/
(the\
is necessary to mean "a litteral/
", because/
bounds the regex, see the snippet below)- and so on
var t = "We have this 8/8 / 69 structure in the text/another text and we want to grab it and 1/2/3";
console.log(t.match(/[0-9]+ *\/ *[0-9]+ *\/ *[0-9]+/g));
(note that in this snippet I used the g
modifier to find multiple occurrences)
If you want to limit copy-paste, or have a need to accept series of 1 to n numbers, you can use a repetition operator:
/[0-9]+( *\/ *[0-9]+){2}/ # 3 numbers (1 number then exactly 2 slash-and-number)
/[0-9]+( *\/ *[0-9]+){1,4}/ # 2 to 5 numbers
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745080001a4610066.html
regex
. What is the regex you used, and how? – trincot Commented Mar 3 at 18:05