简体   繁体   中英

regex to start with a capturing group

I have this regEx to match the following patterns:

/(((fall|spring|summer)\s\d{4});|(waived)|(sub\s[a-zA-Z]\d{3}))/ig

Should match:

fall 2000;
spring 2019; waived
summer 1982; sub T676

Should not match ANY string that does not start with the first capturing group ((fall|spring|summer)\\s\\d{4}) such as:

waived Fall 2014;
sub Fall 2011; waived

To make sure that each matching pattern starts with this group ((fall|spring|summer)\\s\\d{4}) I tried appending ^ in front of the first group like this, /(^((fall|spring|summer)\\s\\d{4});|(waived)|(sub\\s[a-zA-Z]\\d{3}))/ig , but the results were inconsistent.

Demo

You may use

/^(fall|spring|summer)\s\d{4};(?:.*(waived|sub\s[a-zA-Z]\d{3}))?/i

See the regex demo .

Details

  • ^ - start of string
  • (fall|spring|summer) - one of the three alternatives
  • \\s - a whitespace
  • \\d{4} - 4 digits
  • ; - a semi-colon
  • (?:.*(waived|sub\\s[a-zA-Z]\\d{3}))? - an optional sequence of:
    • .* - any 0+ chars other than line break chars, as many as possible (if the values you need are closer to the start of string, replace with a lazy .*? counterpart)
    • ( - start of a grouping construct
      • waived - a waived substring
      • | - or
      • sub - a sub substring
      • \\s - a substring
      • [a-zA-Z] - an ASCII letter
      • \\d{3} - three digits
    • ) - end of the grouping construct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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