如何在第一个空间之前提取所有内容?

时间:2016-09-10 11:57:41

标签: r gsub

public class Child
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ParentID { get; set; }
    [ForeignKey("ParentID")]
    public Parent Parent { get; set; }
}

是我的载体。

我希望得到结果

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,ParentID")] Child child)
    {
        if (ModelState.IsValid)
        {
            int _id;
            do
            {
                _id = new Random().Next();
            } while (await _context.Children.Where(b => b.ID == _id).AnyAsync());

            child.ID = _id;
            _context.Add(child);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        ViewData["ID"] = id;
        return View(child);
    }

我的代码是:

charvct <- c("amc rebel sst","amc ambassador dpl","amc hornet","amc gremlin" ,"amc 1212") 

但输出与输入相同。

1 个答案:

答案 0 :(得分:1)

我们可以匹配&#39; amc&#39;后跟单词边界(\\b)),后跟零个或多个(*)字母数字字符以及空格([[:alnum:] ]),并将其替换为"amc"

sub("amc\\b[[:alnum:] ]*","amc", charvct)
#[1] "amc" "amc" "amc" "amc" "amc"

或捕获&#39; amc&#39;作为一个组((amc))并在替换中我们提供反向引用(\\1

sub("(amc)\\b[[:alnum:] ]*","\\1", charvct)

根据评论中的向量,我们匹配一个或多个标点符号以及空格([[:punct:] ]+),后跟字符,直到字符串末尾(.*)并将其替换为空白( "")。

sub("[[:punct:] ]+.*", '', v1)
#[1] "amc" "bcd" "xyz" "amc" "amc" "dfz"

数据

v1 <- c("amc rebel sst","bcd ambassador dpl","xyz hornet",
                             "amc gremlin" ,"amc 1212(a)" ,"dfz+2")