使用Regex和replace替換一個字串中截取的一字串

來源:互聯網
上載者:User

aspx中:

<table>
                <tr>
                    <td style="width: 178px" colspan="4">
                    <asp:Label id="Label1" runat="server" Text="輸入要截取的字串" CssClass="input_border1"></asp:Label>
                    </td>
                   
                </tr>
                <tr>
                   
                    <td colspan="2" >
   <asp:TextBox id="txtString" runat="server" CssClass="input_border1"></asp:TextBox></td>
                    <td style="width: 621px" colspan="2">
   <asp:Button id="btnSubmit" runat="server" Text="截取" onclick="btnSubmit_Click" CssClass="btn_pic1"></asp:Button>&nbsp;
                    </td>
                </tr>
                <tr>
                  
                    <td style="width: 203px" colspan="4">
   <asp:Label id="lblMessage" runat="server"></asp:Label></td>
                   
                </tr>
            </table>

aspx.cs中:
 public static Regex RX = new Regex(@"^-?[1-9]\d*|[[\u4e00-\u9fa5]+]$",RegexOptions.IgnoreCase);
  protected void btnSubmit_Click(object sender, System.EventArgs e)
  {
            this.lblMessage.Text = "";
            string str = this.txtString.Text;
            if (RX.IsMatch(str))
            {
                int indexBegin = str.IndexOf("[");
                int indexEnd = str.LastIndexOf("]");
                string endstr = str.Substring(indexBegin + 1, indexEnd - indexBegin - 1);//截取“[ ]”裡的文本
                Regex Rx = new Regex(@"[\u4e00-\u9fa5]+", RegexOptions.IgnoreCase);
                String resultStr = "<font color=red>" + endstr + "</font>";
                string ResultAll = Rx.Replace(endstr, resultStr);
                // lblMessage.Text = ResultAll;
                Regex Rex = new Regex(@"[[\u4e00-\u9fa5]+]");
                this.lblMessage.Text = Rex.Replace(str, "[" + ResultAll + "]");
            }
            else
            {
                //return;
                lblMessage.Text = str;
            }
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.