简体   繁体   English

RegExp - 如何检查字符串是否在某个 position 中包含 substring?

[英]RegExp - How to check if a string contains a substring in the certain position?

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" (eg "library/History.read")我有一个类似的字符串:“substring1/substring2.substring3”(例如“library/History.read”)

I need a regular expression to check:我需要一个正则表达式来检查:

  1. the substring1 must be "library" substring1 必须是“库”
  2. the substring2 must have a captial letter at the beginning substring2 必须以大写字母开头
  3. the substring3 must be "read" substring3 必须是“读取”

I'm not familiar with regular expression, the current I wrote is: 'library/([a-zA-Z])\\.(read)' but it is not correct.我对正则表达式不熟悉,我写的当前是: 'library/([a-zA-Z])\\.(read)'但它不正确。 Please help me, thanks!请帮助我,谢谢!

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.是一个字符 class 匹配除换行符以外的任何字符。 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正如彼得所指出的,您的第一个大写字母缺少一个字符 class

Try this regex:试试这个正则表达式:

 testStrings = ["library/History.read", "library/other.read", "library/Geography.read", "library/History.unread", "ebook/hstory.read", "library/StackOverflow.read"] regex = /library\/[AZ][^\.]*\.read/ testStrings.forEach(testString => { console.log(regex.test(testString) + " - " + testString) })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM