#101 解析字串


  • 0

    function strr(str){
    if(str == '' || str == null || str == undefined){
    return [];
    }
    var s = [];
    if(str.indexOf(":") == -1 || str.indexOf(".") == -1){
    return [];
    }
    let s1 = str.split(":");
    for(var i=1;i<s1.length;i++){
    if(s1[i].indexOf(".") != -1){
    s.push(s1[i].split(".")[0]);
    }
    }
    return s;
    }


  • 0

    测试通过:
    const extractStr = (str) => /* TODO /
    {
    var arry=[];
    str.replace(/:([^:|.]
    )./g,function(Regstr,$1){
    arry.push($1);
    });
    console.log(arry);
    return arry;
    }


  • 0

    const extractStr = (str) => {
    const result = str.match(/:+(\w*?).+/g, (...arg) => arg) || [];
    return result.map(item => item.replace(/[:.]/g, ''));
    }


  • 0

    const extractStr = (str) => {
      const result = str.match(/\:+(\w*?)\.+/g, (...arg) => arg) || [];
      return result.map(item => item.replace(/[\:\.]/g, ''));
    }
    

  • 0

    const extractStr = (str) => str.match(/(?<=:)[^:.]+(?=\.)/g)
    

  • 0

    // const extractStr = (str) => str.match(/(?<=:)[^:.]*(?=\.)/g)
    const extractStr = (str) => {
      let t = [];
      str.replace(/\:([^:.]*)\./g, (a, b) => {
        t.push(b)
      })
      return t
    }
    

  • 0

    map 不支持是因为没有匹配到返回 null 而不是 [] 等于调用 null.map()
    可以自己给字符串手动加上一个匹配字符串 再在最终结果里在去掉这个匹配来解决

    匹配左右边界 但是匹配结果不包含左右边界 最好的方案是正向查找 + 反向查找(aks: 先行断言 后行断言 lookhead lookbehind)
    然而mdn告诉我们js只有正向查找 所以匹配结果里无法去掉左边界 就只有slice处理一下了
    对支持正向反向查找的语言 正则如下

    /(?<=:)[^:\.]+(?=\.)/
    

    可以在 http://rubular.com/ 试下


  • 0

    const extractStr = (str) => {
    	let flag = false;
    	let result = [];
    	let current = '';
    	for(let i = 0; i < str.length; i++){
    		let item = str[i];
    		if(item === '.'){
    			if(flag){
    				result.push(current);
    				current = '';
    				flag = false;
    			}
    			continue;
    		}
    
    		if(item === ':'){
    			if(flag){
    				current = '';
    			}else{
    				flag = true;
    			}
    			continue;
    		}
    
    		if(flag){
    			current += item;
    		}
    	}
    	
    	return result;
    };

  • 0

    @jhhfft#101 解析字串 中说:

    const extractStr = (str) => {
      let result = [],
          pattern = /\:+(\w*)\.+/g,
          temp = null
      while(temp = pattern.exec(str)){
        result.push(temp[1])
      }
      return result
    }
    

  • 0

    const extractStr = (str) => {
      const reg = /:([^:\.])*?\./g, arr = [];
      str.replace(reg, item => {
        arr.push(item.substring(1, item.length - 1));
      });
      return arr;
    }
    

  • 0

    const extractStr = (str) =>
    {
    let strArr = str.split(':');
    var newStr = [];
    var n = 0;
    for(let i = 1; i < strArr.length; i++){
    let index = strArr[i].indexOf('.');
    if(index != -1){
    newStr[n] = strArr[i].substring(0,index);
    n++
    }
    }
    return newStr;
    }


  • 0

    const extractStr = (str) => /* TODO */
    {
    var semicolPosition = -1;
    var fullstopPosition = -1;
    var targetArray = [];
    var tempString = "";
    for(var i = 0;i < str.length; i++){
    if(str[i] ===":"){
    semicolPosition = i;
    }
    if(str[i] ==="."){
    fullstopPosition = i;
    }
    if(semicolPosition !== -1 && fullstopPosition !== -1 && fullstopPosition > semicolPosition){
    targetArray.push(str.slice(semicolPosition+1,fullstopPosition));
    semicolPosition = -1;
    fullstopPosition = -1;
    }
    }
    return targetArray;

    }


  • 0

    const extractStr = (str) => {
      let strs = []
      str.replace(/\:([^\:^\.]*?)\./g, function (all, sub) {
        strs.push(sub)
      })
      return strs
    }
    

  • 0

    const extractStr = (str) => {
    const ret = str.match(/(:\w*.)/g) || []
    return ret.map((v) => {
    return v.replace(/:(\w*)./, "$1")
    })

    }


  • 0

    const extractStr = (str) => {
    let a = [];
    str.split(":").forEach((item, index) => {
    if (index !== 0) {
    if (item.split(".").length > 1) {
    a.push(item.split(".")[0])
    }
    }
    });
    return a
    }


  • 0

    @Edge#101 解析字串 中说:

    通过

    const extractStr = (str) => {
    let reg = /:[^:.]*?./g;
    return (str.match(reg) || []).map(v => v.replace(/[:.]/g, ''));
    }


  • 0

    const extractStr = (str) => {
    const ret = str.match(/:+\w*.+/g)

    if (ret === null) {
    return []
    }

    return ret.map(v => v.replace(/[:.]/g, ''))
    }


  • 0

    const extractStr = (str) => {
    var arr = str.split("");
    var crr = [];
    var func = function(){
    if(arr.indexOf(":")!==-1&&arr.indexOf(".")!==-1){
    if(arr.indexOf(":")<arr.indexOf(".")){
    var brr = arr.slice(arr.indexOf(":")+1,arr.indexOf("."));
    brr.splice(0,brr.lastIndexOf(":")+1);
    crr.push(brr.join(""));
    }
    arr.splice(0,arr.indexOf(".")+1);
    func()
    }
    }
    func()
    return crr;
    }


  • 0

    代码略长,但是是比较传统的字符串解析方式做的。
    因为篇幅,所以没用状态机,若用了丑陋了 if / else

    const extractStr = str => {
        const TOKEN_START = "S";
        const TOKEN_END = "E";
        const TOKEN_OTHER = "O";
        const STATUS_NOT_KEY_WORDS = "NK";
        const STATUS_KEY_WORKDS = "K";
        let i = 0;
        let tokens = [];
        while (i < str.length) {
            let c = str[i];
            if (c === ":")
                tokens.push({
                    type: TOKEN_START
                });
            else if (c === ".")
                tokens.push({
                    type: TOKEN_END
                });
            else
                tokens.push({
                    type: TOKEN_OTHER,
                    value: c
                });
            i++;
        }
        let result = [];
        let item = [];
        let token;
        i = 0;
        let status = STATUS_NOT_KEY_WORDS;
        while (i < tokens.length) {
            token = tokens[i++];
            if (token.type === TOKEN_START) {
                if (status === STATUS_NOT_KEY_WORDS) {
                    status = STATUS_KEY_WORKDS;
                    continue;
                }
                if (item.length > 0) {
                    item = [];
                }
            }
            if (token.type === TOKEN_OTHER && status === STATUS_KEY_WORKDS) {
                item.push(token.value);
                continue;
            }
            if (token.type === TOKEN_END && status === STATUS_KEY_WORKDS) {
                result.push(item.join(""));
                item = [];
                status = STATUS_NOT_KEY_WORDS;
                continue;
            }
        }
        return result;
    };
    

  • 0

    const extractStr = (str) => /* TODO */
    {
    let arr = [],flag = 0,temp = ''
    for (let i = 0; i < str.length; i++) {
    if (flag == 0) {
    if(str[i] == ':') {
    flag = 1
    }
    } else if (flag == 1) {
    if (str[i]=='.') {
    flag = 0
    arr.push(temp)
    temp = ''
    }
    if (str[i] == ':') {
    temp = ''
    }
    if (str[i] != ':' && str[i] != '.') {
    temp += str[i]
    }
    }

    }
    return arr
    }


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待