如何从整体中获取字符串

时间:2016-08-04 04:24:55

标签: c# asp.net asp.net-mvc

我有一个字符串,其文字类似于:

  

电子书/ AspNetBook.Pdf / .NetBook

  

电子书/ Asp.Net / AspNetBook.Pdf / .NetBook

或者可能是这个

  

电子书/ Asp.Net / .NetBook / AspNetBook.Pdf

这意味着字符串可能带有许多正斜杠,并且它不会以修复格式出现。我想从这个字符串中获取文件名及其分机AspNetBook.Pdf

我试图让字符串使用子字符串或在句点之前替换字符但是没有得到正确的结果。

4 个答案:

答案 0 :(得分:1)

如果您的字符串始终具有该特定形式string1/string2/string3,则可以使用简单的字符串拆分或正则表达式。

var xx = input.Split('/')[1];

或者

var xx = Regex.Match(input, @".+/(.+)/.+").Groups[1].Value;

请注意,这不包含错误检查,例如,如果输入与给定的表单

不匹配

答案 1 :(得分:0)

这可能会对你有帮助。

ERROR: Spider error processing <GET https://n0where.net/>
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/twisted/internet/base.py", line 824, in runUntilCurrent
    call.func(*call.args, **call.kw)
  File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 638, in _tick
    taskObj._oneWorkUnit()
  File "/usr/lib/python2.7/dist-packages/twisted/internet/task.py", line 484, in _oneWorkUnit
    result = next(self._iterator)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 57, in <genexpr>
    work = (callable(elem, *args, **named) for elem in iterable)
--- <exception caught here> ---
  File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 96, in iter_errback
    yield next(it)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/contrib/spidermiddleware/offsite.py", line 26, in process_spider_output
    for x in result:
  File "/usr/local/lib/python2.7/dist-packages/scrapy/contrib/spidermiddleware/referer.py", line 22, in <genexpr>
    return (_set_referer(r) for r in result or ())
  File "/usr/local/lib/python2.7/dist-packages/scrapy/contrib/spidermiddleware/urllength.py", line 33, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/usr/local/lib/python2.7/dist-packages/scrapy/contrib/spidermiddleware/depth.py", line 50, in <genexpr>
    return (r for r in result or () if _filter(r))
  File "/home/admin/nowhere/thehack/spiders/thehack_spider.py", line 14, in parse
    item['title'] = article.css('.article-title::text').extract_first()
exceptions.AttributeError: 'SelectorList' object has no attribute 'extract_first'

因为你想获得2个正斜杠之间的字符串。这将为您提供所需的正确输出。

The output is the desired string

答案 2 :(得分:0)

试试这个:

string st = "Ebook/AspNetBook.Pdf/.NetBook";
string out = st.Split('/')[1];

请注意,只有在输入中始终有/并且始终是第二个值时才会有效。

答案 3 :(得分:-1)

这里p1将找到'/'的第一个索引,而p2将在p1之后找到'/'的索引。

String text= "Ebook/AspNetBook.Pdf/.NetBook";
int p1=text.indexOf('/');   
int p2=-1;
if(p1!=-1)
p2=text.indexOf('/',p1+1);

if(p1!=-1&&p2!=-1)
System.out.print(text.substring(p1+1,p2);