简体   繁体   English

JS:“正则表达式模式”? OR字符串结尾”

[英]JS : regex pattern “? OR end of string”

The strings are of two different types, I have a solution for each of them but I'm looking for a combined solution. 字符串有两种不同的类型,我为每个字符串都有一个解决方案,但我正在寻找一个组合的解决方案。 For both I need the id '28ae569'. 对于这两者,我都需要输入id'28ae569'。

Solved using : /.*\\/.*-(.*)\\?/ 使用: /.*\\/.*-(.*)\\?/

Solved using : /.*\\/.*-(.*)$/ 使用: /.*\\/.*-(.*)$/解决

So what I'm trying to tell the regex is ' ? 所以我想告诉正则表达式是' OR end of string '. 或字符串 ' 的结尾

I've tried using ' \\?|$ 'but it did not work, it gives me the whole '28ae569?param1=category~%5b715507%7c208524%5d&bi=1&ps=200' in the first case. 我尝试使用' \\?|$ ',但是没有用,在第一种情况下,它给了我整个'28ae569?param1 = category〜%5b715507%7c208524%5d&bi = 1&ps = 200'。 I also tried a number of other combinations, but I'm now shooting arrows in the dark. 我还尝试了许多其他组合,但现在正在黑暗中射击箭。

You need to be more specific when using alternation using the pipe ( | ). 使用管道( | )交替使用时,需要更加具体。 You can use the following regex: 您可以使用以下正则表达式:

/([a-f\d]{3,})(?:\?|$)/i

([af\\d]{3,}) matches the required hexadecimal string. ([af\\d]{3,})与所需的十六进制字符串匹配。 It also makes sure the string is at least 3 characters long. 它还确保该字符串至少3个字符长。 You can adjust this as per your requirements, or just change the quantifier to + if you don't mind single-digit strings like 0 being captured. 您可以根据自己的要求进行调整,如果不介意捕获0等单个数字字符串,则可以将量词更改为+

Note the parentheses around the alternation: (?:\\?|$) — it specifies that it should match either a ? 注意交替符的括号: (?:\\?|$) -它指定它应与?匹配? or the end of the string. 字符串的结尾。 (?:...) is a non-capturing group . (?:...)是一个非捕获组

With your previous regex, it would mean: match either .*\\/.*-(.*)\\? 使用您以前的正则表达式将意味着:匹配.*\\/.*-(.*)\\? or the end of the string, which is not what you want. 字符串的结尾,这不是您想要的。

RegEx Demo 正则演示

Match consecutive digits followed by ? 匹配连续的数字,后跟? or $ , whichever comes first in the input string, as group 1. $ ,以输入字符串中的第一个为准,作为组1。

/([a-fA-F0-9]+)(?:\?|$)/

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

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