Matching text between hyphens with regex

非 Y 不嫁゛ 提交于 2019-12-01 17:38:24

问题


Currently I have this string

"RED-CURRENT_FORD-something.something"

I need to capture the word between the hypens. In this case the word CURRENT_FORD

I have the following written

\CURRENT_.*\B-\

Which returns CURRENT_FORD- which is wrong on two levels.

  1. It implies that everything between hyphens starts with CURRENT
  2. It includes the hyphen at the end.

Any more efficient way of capturing the words in between the hyphens without explicitly stating the first word?


回答1:


You can use the delimiters to help bound your pattern then capture what you want with parentheses.

/-([^-]+)-/

You can then trim the hyphens off.




回答2:


You can use these regex

(?<=-).*?(?=-)//if lookaround is supported

OR

-(.*?)-//captured in group1

.*? matches any character i.e. . 0 to many times i.e. * lazily i.e ?

(?<=-) is a zero width look behind assertion that would match for the character - before the desired match i.e .*? and (?=-) is a zero width look ahead assertion that matches for - character after matching .*?




回答3:


(?<=-)\w+(?=-)

any sequence or "word"-characters, between hyphens which do themselves not take part in the capture (look-behind and look-ahead conditions)




回答4:


Try using the word boundary option:

/^.*-\b(\w+)\b-.*$/

This is actually 3 (well, 2) parts:

^.*-\b

says all characters from the beginning of the token until a dash followed by a word boundary (an invisible boundary between 'word characters' and non 'word characters')

(\w+)

captures the bit between the dashes and puts it into a matched pattern variable (that's what the brackets are for)

The last part is just a repeat of the first part to match any other characters after the dash.



来源:https://stackoverflow.com/questions/13291494/matching-text-between-hyphens-with-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!