我在R上工作。我想提取向量中最后一个空格和字符串模式(“ -APPLE”)之间的所有数字。这些数字可以是可变长度的。
<?php
session_start();
if(isset($_POST['login'])){
//echo "process login";
$doc = new DOMDocument('1.0', 'utf-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
//load XML
$xmlPath = "users.xml";
$doc->load($xmlPath);
//root element
$users = $doc->getElementsByTagName("users")[0];
//create a new <user> element
$user = $doc->createElement("user");
//create the role attribute and append to <person>
$attr = $doc->createAttribute("id");
$attr->value =""; // yet not incrementing values
//$attr->value = count(preceding::user) + 1;
$user->appendChild($attr);
//create an element <username> and get a value from textbox and post to xml file
$username = $doc->createElement("username");
$usernameText = $doc->createTextNode($_POST['username']); //this should be sanitized
$username->appendChild($usernameText);
//assign textfield value to root element in xml file
$user->appendChild($username);
$users->appendChild($user);
//to print multiple chatroom files from xml file
$xml = simplexml_load_file("chatrooms.xml");
foreach ($xml as $chatroom)
{
print "<a href = ' $chatroom->chatroomname ' >" . $chatroom->chatroomname . "</a>" . '<br />';
}
}
?>
预期结果集应为向量,如c(2,25,567,NA)
答案 0 :(得分:1)
有关使用Regex group capture in R with multiple capture-groups软件包中的str_match()
的示例,请参见stringr
。
在您的情况下:
> test_string = c("ABC 2-APPLE", "123 25-APPLE", "DEF GHI 567-APPLE")
>
> library(stringr)
> x <- str_match(test_string, " ([0-9]+)-APPLE$")[,2]
> as.numeric(x)
[1] 2 25 567
答案 1 :(得分:1)
您可以使用“ rebus”软件包,该软件包在创建所需的regex模式时非常用户友好。
killed