简体   繁体   English

Javascript正则表达式在_和-之间找到字符串

[英]Javascript Regex find string between _ and -

I'm trying to work out the regex to get the en part of the string word_en-gb 我正在尝试计算正则表达式以获取字符串word_en-gben部分

I'm using .match(); 我正在使用.match(); eg 例如

var string = "word_en-gb";
string.match(/(?<=\_)(.*?)(?=\-)/);

This (?<=\\_)(.*?)(?=\\-) works on regex101.com but when I use it in my code I get the error Uncaught SyntaxError: Invalid regular expression: /(?<=_)(.*?)(?=-)/: Invalid group 这个(?<=\\_)(.*?)(?=\\-)regex101.comregex101.com但是当我在代码中使用它时,出现错误Uncaught SyntaxError: Invalid regular expression: /(?<=_)(.*?)(?=-)/: Invalid group

and

\\_(.*?)\\- matches on regex101 but produces _en-,en \\_(.*?)\\-在regex101上匹配,但产生_en-,en

Lookbehind isn't available in Javascript regex. Lookbehind在Javascript正则表达式中不可用。 You can use captured group #1: 您可以使用捕获的组#1:

var string = "word_en-gb";
string.match(/_(.*?)(?=-)/);
//=> ['_en', 'en']

Or negation: 或否定:

string.match(/_([^-]*)/);
//=> ['_en', 'en']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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