根据R中特定字符的相对位置从字符串中删除字符

时间:2015-05-09 09:56:47

标签: regex r

如何删除所有字符 " p"和" p"本身,在v1的所有字符串中,如下面的数据框中那样。

df1 <- data.frame(v1 = c("m0p1", "m5p30", "m11p20", "m59p60")) 

如何删除所有字符 &#34; p&#34;和&#34; p&#34;本身? 谢谢

3 个答案:

答案 0 :(得分:4)

您可以使用gsub

# Remove everything before p
gsub("^.*?p(.*)","\\1",df1$v1,perl=TRUE)
#[1] "1"  "30" "20" "60"

# Remove everything after p
gsub("(.*)?p.*$","\\1",df1$v1,perl=TRUE)
# [1] "m0"  "m5"  "m11" "m59"

答案 1 :(得分:2)

您也可以

sub('^[^p]*p', '', df1$v1)
#[1] "1"  "30" "20" "60"

或者

sub('p.*$', '', df1$v1)
#[1] "m0"  "m5"  "m11" "m59"

答案 2 :(得分:1)

在p:

之后
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

</head>

<body>

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

</body>
</html>

在p:

之前
gsub('.*(?<=p)(\\d+)','\\1',df1$v1,perl=T)