【问题标题】:Using regex function to manipulate string in c#使用正则表达式函数在c#中操作字符串
【发布时间】:2013-06-12 01:52:54
【问题描述】:

我想在 c# 中使用正则表达式从下面的字符串中删除 jsessionid=99171C97AE28712E048E321DB6B192F3

www.ploscompbiol.org/article/fetchObjectAttachment.action;jsessionid=99171C97AE28712E048E321DB6B192F3?uri=info%3Adoi%2F10.1371%2Fjournal.pone.0066655&representation=XML

我试过了

string id = id.Replace(";jsessionid=.*?(?=\\?|$)", "");

但它不起作用,请帮助!

【问题讨论】:

  • 那是string.Replace,而不是Regex.Replace。此外,我无法从我不知道的站点下载文件。发布实际的 XML。
  • 我不认为发布实际的 XML 会有任何不同。我只需要阻止jsessionid 附加到网址或将其删除。

标签: c# regex jsessionid


【解决方案1】:
Regex.Replace(text, "jsessionid=[^\\?]+","")

【讨论】:

  • 谢谢 现在工作正常。
【解决方案2】:

如果您改变主意并且不想使用 RegEx 而是使用 string.replace 函数进行管理,

        string sample = "ansjsessionid=99171C97AE28712E048E321DB6B192F3wer";
        sample = sample.Replace( sample.Substring(sample.IndexOf("jsessionid="),43),"");

请注意,我假设 ID 始终为 32 个字符。

【讨论】:

    【解决方案3】:

    您可以使用以下方法删除 jsession。

    Regex rgx = new Regex("jsessionid=[^\\?]*)");
    string id = rgx.Replace(line,"");
    

    【讨论】:

    • string.Replace 无法正常工作并浏览此站点,一些建议的 string.replaceAll,我找不到。
    • 他们可能一直在谈论具有replaceAll 方法的Java。为此,只需使用正则表达式替换
    【解决方案4】:

    不使用正则表达式的解决方案:

    var url = @"www.ploscompbiol.org/article/fetchObjectAttachment.action;jsessionid=99171C97AE28712E048E321DB6B192F3?uri=info%3Adoi%2F10.1371%2Fjournal.pone.0066655&representation=XML";
    
    var startIndex = url.IndexOf("jsessionid=");
    var endIndex = url.IndexOf('?', startIndex);
    url.Remove(startIndex, endIndex - startIndex);
    

    注意如果没有找到'?',那么它会抛出异常。

    【讨论】:

      猜你喜欢
      • 2013-04-01
      • 2011-12-20
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多