问题
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.
- It implies that everything between hyphens starts with
CURRENT
- 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