javascript - Get NumberNumberNumber structure in the given string - Stack Overflow

I have a string like this:const string = 'We have this 8869 structure in the textanother tex

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.

Share Improve this question asked Mar 3 at 17:43 soroosh azadisoroosh azadi 631 silver badge4 bronze badges 1
  • 6 You tagged this with regex. What is the regex you used, and how? – trincot Commented Mar 3 at 18:05
Add a comment  | 

1 Answer 1

Reset to default 2

You 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

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信