javascript - RegExp - How to check if a string contains a substring in the certain position? - Stack Overflow

I tried to search this question first but didn't found what I need, here is it:I have a string li

I tried to search this question first but didn't found what I need, here is it:

I have a string like: "substring1/substring2.substring3" (e.g. "library/History.read")

I need a regular expression to check:

  1. the substring1 must be "library"
  2. the substring2 must have a captial letter at the beginning
  3. the substring3 must be "read"

I'm not familiar with regular expression, the current I wrote is: 'library/([a-zA-Z])\\.(read)' but it is not correct. Please help me, thanks!

I tried to search this question first but didn't found what I need, here is it:

I have a string like: "substring1/substring2.substring3" (e.g. "library/History.read")

I need a regular expression to check:

  1. the substring1 must be "library"
  2. the substring2 must have a captial letter at the beginning
  3. the substring3 must be "read"

I'm not familiar with regular expression, the current I wrote is: 'library/([a-zA-Z])\\.(read)' but it is not correct. Please help me, thanks!

Share Improve this question asked Mar 9, 2021 at 23:36 MeilanMeilan 4841 gold badge10 silver badges27 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

There are many ways to solve regex problems, starting from your own attempt here's something that works! :-)

library/([A-Z][a-zA-Z]+)\.(read)

You had three small mistakes:

  • . is a character class matching any character except newline. Escape your . like this \. not like this \\.; and
  • Your first capture group was matching exactly one letter. You missed the quantifier. Use the + qunatifier to match one or more.
  • As pointed out by Peter, you were missing a character class for your first capital letter

Try this regex:

testStrings = ["library/History.read", "library/other.read", "library/Geography.read", "library/History.unread", "ebook/hstory.read", "library/StackOverflow.read"]
regex = /library\/[A-Z][^\.]*\.read/

testStrings.forEach(testString => {
  console.log(regex.test(testString) + " - " + testString)
})

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744167824a4561390.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信