如何循环所有与正则表达式匹配的元素?

时间:2009-08-03 12:22:49

标签: javascript regex

以下是这种情况: 我想找到与正则表达式相匹配的元素......

  

targetText =“SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext”

我在这样的javascript中使用正则表达式

reg = new RegExp(/e(.*?)e/g);   
var result = reg.exec(targetText);

我只得到第一个,但不是跟随.... 我只能获得T1,但不能获得T2,T3 ......

8 个答案:

答案 0 :(得分:61)

var reg = /e(.*?)e/g;
var result;
while((result = reg.exec(targetText)) !== null) {
    doSomethingWith(result);
}

答案 1 :(得分:11)

尝试在字符串而不是exec()上使用match(),尽管您也可以使用exec循环。比赛应该一次性给你所有的比赛。我想你也可以省略全局说明符。

reg = new RegExp(/e(.*?)e/);   
var matches = targetText.match(reg);

答案 2 :(得分:9)

取决于你想用它做什么的三种方法:

  • 遍历每场比赛:.match

    targetText.match(/e(.*?)e/g).forEach((element) => {
       // Do something with each element
    });
    
  • 循环播放并动态替换每个匹配:.replace

    const newTargetText = targetText.replace(/e(.*?)e/g, (match, $1) => {
      // Return the replacement leveraging the parameters.
    });
    
  • 循环播放并即时执行操作:.exec

    const regex = /e(.*?)e/g;  // Must be declared outside the while expression, 
                               // and must include the global "g" flag.
    
    let result;
    while(result = regex.exec(targetText)) {
      // Do something with result[0].
    } 
    

答案 3 :(得分:2)

targetText = "SomeT1extSomeT2extSomeT3extSomeT4extSomeT5extSomeT6ext"    
reg = new RegExp(/e(.*?)e/g);   
var result;
while (result = reg.exec(targetText))
{
    ...
}

答案 4 :(得分:1)

按照上面的建议,我不断遇到无限循环,例如:

var reg = /e(.*?)e/g;
var result;
while((result = reg.exec(targetText)) !== null) {
    doSomethingWith(result);
}

每次分配给result的对象是:

["", "", index: 50, input: "target text", groups: undefined]

因此,就我而言,我将上面的代码编辑为:

const reg = /e(.*?)e/g;
let result = reg.exec(targetText);
while(result[0] !== "") {
    doSomethingWith(result);
    result = reg.exec(targetText);
}

答案 5 :(得分:0)

您还可以使用String.replace方法遍历所有元素。

use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;

use serde; // 1.0.85
use serde::de::{self, Deserialize, MapAccess, Visitor}; // 1.0.85
use serde::Deserializer;
use serde_derive::Deserialize; // 1.0.85
use toml; // 0.4.10
use void::Void; // 1.0.2

#[derive(Debug)]
struct Obj {
    x: isize,
    y: String,
}

struct ObjVisitor;

// OjbAux is here to avoid implement the deserialiser of the map by hand we can't use
// Obj cause it will cause infinite recursion
#[derive(Debug, Deserialize)]
struct ObjAux {
    x: isize,
    y: String,
}

impl<'de> Visitor<'de> for ObjVisitor {
    type Value = Obj;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("string or map")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(FromStr::from_str(value).unwrap())
    }

    fn visit_map<M>(self, visitor: M) -> Result<Self::Value, M::Error>
    where
        M: MapAccess<'de>,
    {
        let aux: ObjAux = Deserialize::deserialize(de::value::MapAccessDeserializer::new(visitor))?;
        Ok(Obj { x: aux.x, y: aux.y })
    }
}

impl<'de> Deserialize<'de> for Obj {
    fn deserialize<D>(deserializer: D) -> Result<Obj, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(ObjVisitor)
    }
}

impl FromStr for Obj {
    type Err = Void;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Obj {
            x: 0,
            y: s.to_owned(),
        })
    }
}

#[derive(Debug, Deserialize)]
struct Simple {
    obj: Obj,
}

#[derive(Debug, Deserialize)]
struct InsideHashMap {
    objs: HashMap<String, Obj>,
}

fn main() {
    // Basic deserialization of Obj
    let toml = r#"
        x = 5
        y = "hello"
    "#;
    let obj: Obj = toml::from_str(toml).unwrap();
    println!("{:?}", obj);

    // Basic deserialization of Obj as a field in a struct
    let toml = r#"
        [obj]
        x = 5
        y = "hello"
    "#;
    let simple: Simple = toml::from_str(toml).unwrap();
    println!("{:?}", simple);

    // Basic deserialization of Obj as a field in a struct as a string or struct
    let toml = r#"
        obj = "hello"
    "#;
    let simple: Simple = toml::from_str(toml).unwrap();
    println!("{:?}", simple);

    // Deserialization of an Obj inside a HashMap
    let toml = r#"
        [objs]
        a = { x = 5, y = "hello" }
    "#;
    let working: InsideHashMap = toml::from_str(toml).unwrap();
    println!("{:?}", working);

    // Deserialization of Obj inside a HashMap field as a string or struct
    let toml = r#"
        [objs]
        a = "hello"
    "#;
    let not_working: InsideHashMap = toml::from_str(toml).unwrap();
    println!("{:?}", not_working);
}

问候

答案 6 :(得分:0)

我实际上正在处理这个问题。我更喜欢Lambda函数来处理所有事情。

reg = /e(.*?)e/gm;   
var result = reg.exec(targetText);

result.forEach(element => console.log(element));

答案 7 :(得分:0)

我是在控制台会话(Chrome)中完成的。

> let reg = /[aeiou]/g;
undefined
> let text = "autoeciously";
undefined
> matches = text.matches(reg);
(7) ["a", "u", "o", "e", "i", "o", "u"]
> matches.forEach(x =>console.log(x));
a
u
o
e
i
o
u