[英]JavaScript: Extract part of string between two optional characters with Regex
I'm working on a regex in javascript for capturing part of the string between two optional characters. 我正在使用javascript中的正则表达式来捕获两个可选字符之间的部分字符串。
Optional characters are: '=' and '||' 可选字符为:'='和'||'
Scenarios: 场景:
For getting the value after '||' 用于获取'||'之后的值 I manage that with the split() function.
我用split()函数来处理。
For getting the 'A simple message' part I manage to extract the string with the regex match(/\\=(.*)\\|\\|/).pop()
when both '=' and '||' 为了获得“简单消息”部分,我设法同时使用'='和'||'时使用正则表达式
match(/\\=(.*)\\|\\|/).pop()
提取字符串match(/\\=(.*)\\|\\|/).pop()
are in the string. 在字符串中。
Any suggestions for extracting the string with one regex when one of the two optional characters is there? 有两个可选字符之一时,用一个正则表达式提取字符串的任何建议吗?
I tried also /(\\=)?(.*)(\\|\\|)?/
but is not working. 我也尝试了
/(\\=)?(.*)(\\|\\|)?/
但没有用。
You can use this negative lookahead based regex to capture value from =
and optional ||
您可以使用基于负前瞻的正则表达式从
=
和可选||
捕获值。 : :
/=((?:(?!\|\|).)*)/
This should probably do what you want: 这可能应该做您想要的:
^LENGTH(?:=([^|]*))?(?:\|\|(\d+))?$
This will match both the part between LENGTH=
and ||
这将匹配
LENGTH=
和||
之间的部分 and the part after that. 之后的部分。 Both will be returned in the result, when present.
如果存在,两者都将返回结果。
Example: 例:
[
"LENGTH=A simple message||5",
"LENGTH=A simple message",
"LENGTH||5"
].forEach(function(string)
{
var result = string.match(/^LENGTH(?:=([^|]*))?(?:\|\|(\d+))?$/);
console.log("found:",result[1],result[2]);
});
Of course, there are a few assumptions here regarding the actual format of the data. 当然,这里有一些关于数据实际格式的假设。
Output: 输出:
found: A simple message / 5
found: A simple message / undefined
found: undefined / 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.