简体   繁体   中英

Find pattern inside string regex

I need to find if some pattern is exist in the following string

I123456-sxzzukerrdco86rg-CMafApp-java

Or D977058-sxzzukerrdco86rg-CMafApp-java

I need to find the following

  1. if string start with I977058-
  2. The I can be also D like D977058-
  3. the string should be find in the start of the string like I977058-sxzzukerrdco86rg-CMafApp-java , it cannot be in any other part of the string…
  4. zzzz-sxzzukerrdco86rg-CMafApp-java is not valid
  5. 11111-sxzzukerrdco86rg-CMafApp-java not valid

I try with the following which doesn't works

I don't know how to provide pattern which take also the D or I as starting point

var res = str.match(/I-/g);

不能完全清楚您要匹配的内容,但是以下模式将匹配任何以“ D”或“ I”开头的字符串-^字符表示字符串的开头。

var res = str.match(/^[ID]/);

You could check against the two letters and the wanted digits and a dash.

 console.log([ 'I123456-sxzzukerrdco86rg-CMafApp-java', 'D977058-sxzzukerrdco86rg-CMafApp-java', 'foo' ].map(/./.test.bind(/^[DI]\\d{6}-/))); 

Try something like that :

/^[ID]/

The '^' tells that it is the beginning of the word. [ID] => get a char in group {I,D}

You can use this website to train and understand regexpressions : https://regex101.com/

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