在JavaScript中,如何编写正则表达式以查找第10个位置的确切单词?

huangapple go评论81阅读模式
英文:

How to write regular expression to find exact word at 10th position in Javascript adobe?

问题

I want to get result as CON from above line in adobe classification rule builder code which i have been using to get the desired output is

我想从上述行中获取CON作为结果,我一直在使用的Adobe分类规则生成器代码来获取所需的输出是

^(.+?)_(.+?)_(.+?)_(.+?)_(.+?)_(.+?)_(.+?)_(.+?)_(.+?)_(.+?)_(.+?)$

however this code only give output as any word which is at 10th position? I want to get output which matches CON and is at 10th position.

但是,这段代码只会输出位于第10个位置的任何单词?我想要获取匹配CON并且位于第10个位置的输出。

英文:

I have been trying to write regular expression which find a specific word at specific position in javascript adobe classification rule builder

DI_NEO_OP_BRA_CRC_LRN_DIS_EP_NA_CON_UC_NA  

I want to get result as CON from above line in adobe classification rule builder code which i have been using to get the desired output is

^(.+?)\_(.+?)\_(.+?)\_(.+?)\_(.+?)\_(.+?)\_(.+?)\_(.+?)\_(.+?)\_(.+?)\_(.+?)$

however this code only give output as any word which is at 10th position? I want to get output which matches CON and is at 10th position.

答案1

得分: 1

可以使用一个捕获组,然后匹配"CON"后面要么是下划线("_")要么是字符串结尾:

^(?:[^_\n]*_){9}(CON)(?:_|$)

解释

  • ^ 字符串的开始
  • (?:[^_\n]*_){9} 重复9次,匹配除了下划线("")和换行符之外的任何字符,然后匹配下划线("")
  • (CON) 捕获组1,匹配"CON"
  • (?:_|$) 匹配下划线("_")或者断言字符串的结尾

正则表达式演示

英文:

You can use a single capture group, and then match CON followed by either _ or the end of the string:

^(?:[^_\n]*_){9}(CON)(?:_|$)

Explanation

  • ^ Start of string
  • (?:[^_\n]*_){9} Repeat 9 times matching any character except _ or a newline, and then match _
  • (CON) Capture group 1, match CON
  • (?:_|$) Match either _ or assert the end of the string

Regex demo

答案2

得分: 0

(?<=              # 匹配后
  ^               # 行的开始,然后
  (?:[^_]+_)      #         1+ 个非下划线字符后跟 '_',
  {9}             # 9 次
)                 # 
CON               # 字面上的 'CON',
(?=_|$)           # 后面跟 '_'' 或行的结束。

regex101.com上试试

英文:
(?&lt;=              # Match after
  ^               # the beginning of the line, then
  (?:[^_]+_)      #         1+ non-underscore chars followed by &#39;_&#39;,
  {9}             # 9 times
)                 # 
CON               # literal &#39;CON&#39;,
(?=_|$)           # followed by &#39;_&#39; or end of line.

Try it on regex101.com.

huangapple
  • 本文由 发表于 2023年3月31日 19:01:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定