简体   繁体   中英

Javascript regular expression how to?

How do I construct a regular expression to search a larger string for a substring that looks like:

"x bed" OR "x or y bed"

In both cases I will need access to both variables x and y, which are both integers.

Any help appreciated....

(?:\d+ or )?\d+ bed

捕获“ x床”并添加可选的“ x或”

Try this

(\d+)\s+or\s+(\d+)\s+bed|(\d+)\s+bed

Hth!

With JavaScript -

var subject = "1 bed,2 or 3 bed"
var myregexp = /(\d+) bed|(\d+) or (\d+) bed/img;
var match = myregexp.exec(subject);
while (match != null) {
    if (match[1]) {
         alert("Found 'x bed', x is '" + match[1] + "'");    
    }
    else {
        alert("Found 'x or y bed', x is '" + match[2] + "', y is '" + match[3] + "'");   
    }    

    match = myregexp.exec(subject);
}

Demo - http://jsfiddle.net/ipr101/WGUEH/

I'm assuming that you want this type of output:

"23 bed"           => "23"
"32 or 45 bed"     => "32", "45"
"4"                => no matches
"99 or bed"        => no matches
"or bed"           => no matches

If that's a correct interpretation of what you want, then you can use this regex:

/(\\d+)\\s+bed|(\\d+)\\s+or\\s+(\\d+)\\s+bed/

And this is the outline of the code to use it

var str = "32 or 45 bed";
var matches = str.match(/(\d+)\s+bed|(\d+)\s+or\s+(\d+)\s+bed/);
if (matches) {
    alert(matches[1]);      // first numeric match
    alert(matches[3]);      // second numeric match (null if not present)
}

You can see a test bed here:

http://jsfiddle.net/jfriend00/9n5XK/

By way of explanation, the regex is in two parts. The first piece is this:

(\d+)\s+bed

any sequence of digits that are captured
followed by any amount of whitespace
followed by "bed"

The second piece is this:

(\d+)\s+or\s+(\d+)\s+bed/

any sequence of digits that are captured
followed by any amount of whitespace
followed by "or"
followed by any mount of whitespace
followed by any sequence of digits that are captured
followed by any amount of whitespace
followed by "bed"

The regex is set up so that it will match either the first piece of the regex or the second piece of the regex.

So, the captured pieces are going to be in the match array in slots 1, 2 and 3. The way the regex is set up, the first match will be in slot 1 or 2 (whichever is not null) and the second match (if present) will be in slot 3.

I don't claim this is the shortest possible regex that can match this, but it is straightforward to understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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