如何在字符 y 仍在 y 后面时查找字符 x 之前的最后一个文本 Javascript
我试图找到一个优雅的解决方案来解决以下问题。我有以下字符串:
This ) is ) some $ text。 ) lkzejflez $ aaeea ) aeee
存在于粗体标记括号之前的人类可读文本部分和括号之后的纯粹垃圾部分中。我需要在字符串中找到人类可读的文本,就像这个一样。我需要获取最后一个括号(粗体标记)之前的文本,后面仍然有一个美元符号(粗体标记)。这是我对问题的解决方案:
const info = "This)is)$a sentence.)lkzejflez$aaeea)aeee";
let result;
for(let i = 0; i < info.length;i++){
const char = info[i];
const after = info.substring(i+1,info.length);
const otherChance = after.indexOf(')') < after.lastIndexOf('$');
if(otherChance){continue;};
const isEndBracket = char ===')';
const before = info.substring(0,i)
if(isEndBracket){result = before;break;};
}
console.log(result)
预期结果是“This)is)$a句子。”我的代码确实返回了这个结果,但它使用了 substr 和 forloop,其中可以使用正则表达式。但我现在不知道如何。有谁知道我的问题的更优雅的解决方案。提前致谢。
I was trying to find an elegant solution to the following problem. I have the following string :
This ) is ) some $ text. ) lkzejflez $ aaeea ) aeee
Existing out of a part that is human readable text before the bold marked bracket and a part that just plain rubbish after the bracket. I need to find the human readable text in string alike this one. I need to get the text before the last bracket (bold marked) that still has a dollar sign (bold marked) behind it. Here is my solution to the problem :
const info = "This)is)$a sentence.)lkzejflez$aaeea)aeee";
let result;
for(let i = 0; i < info.length;i++){
const char = info[i];
const after = info.substring(i+1,info.length);
const otherChance = after.indexOf(')') < after.lastIndexOf('
The expected result is 'This)is)$a sentence.' My code does return this result but it uses substr and a forloop where regex could be used. I do however not now how. Does anyone know a more elegant solution to my problem. Thanks in advance.
); if(otherChance){continue;}; const isEndBracket = char ===')'; const before = info.substring(0,i) if(isEndBracket){result = before;break;}; } console.log(result)The expected result is 'This)is)$a sentence.' My code does return this result but it uses substr and a forloop where regex could be used. I do however not now how. Does anyone know a more elegant solution to my problem. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试以下正则表达式:
^.*\)(?=.*\$)
说明:从行首到最后一个 ) 匹配尽可能多的字符,后跟 $。
详细解释:贪婪地将行首的零个或多个除换行符之外的任何字符匹配到 ) 字符,该字符后跟零个或多个除换行符之外的任何字符,然后是 $ 符号。
Try the following regex:
^.*\)(?=.*\$)
Explanation: Match as many characters as possible from the start of the line to the last ) that is followed by a $.
Detailed explanation: Greedily match zero or more of any character except a newline from the start of the line to a ) character that is followed by zero or more of any character except a newline and then a $ sign.