我使用平面文本文件作为数据库,因此我需要能够解析.txt。我需要做的第一件事是能够拉出确切的字符串,我正在寻找我感到困惑的东西。我已经看到的其他答案每次都是相同的字符串...但我正在寻找如何在(开始)和(结束)之间拉出文本,其中每次之间的所有内容都是不同的长度。任何帮助?这是我想要的一个例子
String line = sr.ReadToEnd();
// line to get all the text from my file
string whatIWant = stringEditor("beginning", "end", line);
string whatIWant(string first, string second, string whatToParse)
{
//what do I put here to return
//the text from line between first and second
return whatever;
}
答案 0 :(得分:3)
您应该使用String.Substring()
string whatIWant(string first, string second, string whatToParse)
{
return whatToParse.Substring(first.Length, whatToParse.Length - first.Length - second.Length);
}
DotNetFiddle:https://dotnetfiddle.net/h5lNIB
答案 1 :(得分:2)
从this answer获取解决方案,关于如何扩展本机字符串类以获得字符串之间的字符串。
在所有字符串之间创建方法:
public static class Ext
{
public static string Between(this string source, string left, string right)
{
return System.Text.RegularExpressions.Regex.Match(
System.Text.RegularExpressions.Regex.Excape(source),
string.Format("{0}(.*){1}", left, right))
.Groups[1].Value;
}
}
然后它变得非常简单:
"beginning123456end".Between("beginning", "end")
123456
如果你总是使用开头和结尾,那就进一步吧:
public static class Ext
{
public static string BetweenBeginningAndEnd(this string source)
{
return System.Text.RegularExpressions.Regex.Match(
System.Text.RegularExpressions.Regex.Excape(source),
string.Format("{0}(.*){1}", "beginning", "end"))
.Groups[1].Value;
}
}
"beginning123456end".BetweenBeginningAndEnd()
123456
编辑:正如@codenoire所说,你还需要逃避可能的正则表达式字符
答案 2 :(得分:1)
获取开始索引和结束索引,然后使用substring来使用索引获取字符串。
//Bind Params
$sql->bindValue(':r_date', $r_date, PDO::PARAM_STR);
$sql->bindValue(':r_title', $r_title, PDO::PARAM_STR);
$sql->bindValue(':v_name', $v_name, PDO::PARAM_STR);
$sql->bindValue(':v_email', $v_email, PDO::PARAM_STR);
$sql->bindValue(':host', $host, PDO::PARAM_STR);
$sql->bindValue(':host_type', $host_type, PDO::PARAM_STR);
$sql->bindValue(':r_features', $r_features, PDO::PARAM_INT);
$sql->bindValue(':r_security', $r_security, PDO::PARAM_INT);
$sql->bindValue(':r_service', $r_service, PDO::PARAM_INT);
$sql->bindValue(':r_reliability', $r_reliability, PDO::PARAM_INT);
$sql->bindValue(':r_overall', $r_overall, PDO::PARAM_INT);
$sql->bindValue(':thumbs', $thumbs, PDO::PARAM_STR);
$sql->bindValue(':comments', $comments, PDO::PARAM_STR);
//get data from $_POST and execute
$timestamp = time(); //F, j, Y -> Full Month, day of mo w/o leading zeros, full 4-digit year
$r_date = date("F/jS/Y",$timestamp);
$r_title = $_POST['r_title'];
$v_name = $_POST['v_name'];
$v_email = $_POST['v_email'];
$host = $_POST['host'];
$host_type = $_POST['host_type'];
$r_features = $_POST['r_features'];
$r_security = $_POST['r_security'];
$r_service = $_POST['r_service'];
$r_reliability = $_POST['r_reliability'];
$r_overall = ($r_features + $r_security + $r_service + $r_reliability) / 4;
$thumbs = $_POST['thumbs'];
$comments = $_POST['comments'];
var_dump($r_title, $_POST['r_title']);
$sql->execute();