简体   繁体   English

正则表达式匹配包含 2 个字符之间的字符串

[英]Regex Match containing string between 2 characters

I'm trying to match a string in an HTTP page between >< .我正在尝试匹配 HTTP 页面中><之间的字符串。

I'm having trouble with the first > as it also matches subsequent chars.我在使用第一个>遇到问题,因为它也匹配后续字符。 eg.例如。 in this example在这个例子中

<a href="https://stackoverflow.com" class="-logo js-gps-track"
                        data-gps-track="top_nav.click({is_current:false, location:3, destination:8})">
                        <span class="-img _glyph">Stack Overflow</span>
                    </a>

I would only want to match Stack Overflow .我只想匹配Stack Overflow I've currently got \\>([^\\>].*Stack Overflow.*)\\< but that matches everything after the first > ie我目前有\\>([^\\>].*Stack Overflow.*)\\<但这与第一个之后的所有内容匹配>

><span class="-img _glyph">Stack Overflow<

Any help would be great任何帮助都会很棒

It'd probably be more elegant to use DOMParser, and take the textContent of .-img._glyph :使用 DOMParser 并采用.-img._glyphtextContent可能会更优雅:

 const str = `<a href="https://stackoverflow.com" class="-logo js-gps-track" data-gps-track="top_nav.click({is_current:false, location:3, destination:8})"> <span class="-img _glyph">Stack Overflow</span> </a>`; console.log( new DOMParser().parseFromString(str, 'text/html').querySelector('.-img._glyph').textContent );

If you had to use regex, instead of repeating .如果您必须使用正则表达式,而不是重复. (which matches anything), repeat [^<>] (which matches anything which isn't a < or > ) on either side of the Stack Overflow part, while looking ahead and behind for < and > : (匹配任何内容),在Stack Overflow部分的任一侧重复[^<>] (匹配任何不是<> ),同时向前和向后查看<>

(?<=>)[^<>]*Stack Overflow[^<>]*(?=<)

(If you can't use lookbehind, match the initial > and capture everything afterwards, then extract the capture group) (如果不能使用lookbehind,匹配首字母> ,然后捕获所有内容,然后提取捕获组)

Try using lookbehind and lookahead assertions , as in this regex: (?<=>)Stack Overflow(?=<)尝试使用lookbehind 和lookahead assertions ,就像在这个正则表达式中一样: (?<=>)Stack Overflow(?=<)

 const text = `<a href="https://stackoverflow.com" class="-logo js-gps-track" data-gps-track="top_nav.click({is_current:false, location:3, destination:8})"> <span class="-img _glyph">Stack Overflow</span> </a>`; const regex = /(?<=>)Stack Overflow(?=<)/g; const found = text.match(regex); console.log(found);

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

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