将[]括号替换为字符串

时间:2015-02-16 08:34:48

标签: c# sql arrays replace

我有一个包含数字括号[]的字符串。由于此字符串表示SQL数据库的列名,因此我需要删除/替换它们。 到目前为止,我通过以下方式进行:

if (stringWithBracket.Contains("[0]"))
   noBracket = data.Replace("[0]", "0");
if (stringWithBracket.Contains("[1]"))
   noBracket = data.Replace("[1]", "1");
if (stringWithBracket.Contains("[2]"))
   noBracket = data.Replace("[2]", "2");
if (stringWithBracket.Contains("[n]"))
   noBracket = data.Replace("[n]", "n");

它工作正常,但对我来说看起来很难看,因为我必须为[1]到[20]这样做。 有没有办法实现这个"更好的"这意味着我的代码更少?

5 个答案:

答案 0 :(得分:7)

您可以使用Regex.Replace确保仅提取数字:

var pattern = @"\[(\d+)\]";
var replaced = Regex.Replace(stringWithBracket, pattern, "$1"); 

答案 1 :(得分:4)

似乎您要删除所有括号:

data = data.Replace("[",string.Empty).Replace("]",string.Empty);

答案 2 :(得分:3)

所以你基本上想要一个循环?

for (int i = 0; i <= 20; i++)
{
    noBracket = data.Replace(String.Format("[{0}]", i), i);
}

答案 3 :(得分:2)

这是正则表达式擅长的东西:

noBracket = Regex.Replace(stringWithBracket, @"\[(\d+\)]", "$1")

匹配[(需要转义为开头括号通常会启动一个字符组),后跟一个或多个数字,后跟一个右括号。捕获数字(括号),以便可以在替换表达式中使用。

这将替换字符串中的所有匹配项,只替换第一个将需要更复杂的正则表达式只匹配一次。

答案 4 :(得分:0)

class CircleCalendar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      events: [],
      eventSortMenuVisible: false,
      eventSortLabel: "Upcoming Events",
      calendarView: "month",
      loading: true,
      canRender: true,
      visible: false,
      unavailability: []
    };
    this.calendarClick = this.calendarClick.bind(this);
    this.dayClick = this.dayClick.bind(this);
  }

  componentDidMount() {
    this.init();
  }

  async init() {
    await this.props.listEvents({
      circle_id: this.props.circle.id,
      nopaging: 1
    });

    if (
      this.props.events &&
      this.props.events.rows &&
      this.props.events.rows.length
    ) {
      this.props.events.rows.forEach((item, index) => {
        item.start = `${item.start} ${item.start_time} ${item.start_time_delimeter}`;
        item.end = moment(
          `${item.end} ${item.end_time} ${item.end_time_delimeter}`,
          "YYYY-MM-DD HH:mm a"
        );
        item.eventStartEditable = false;
        item.eventDurationEditable = false;
      });
      await this.setState({ events: this.props.events.rows });
    }
    this.setState({ loading: false });

    await this.props.getUserUnavailability({
      circle_id: this.props.circle.id,
      limit: this.state.limit
    });

    if (
      this.props.unavailability &&
      this.props.unavailability.rows &&
      this.props.unavailability.rows.length
    ) {
      this.arrays = [];

      this.props.unavailability.rows.forEach(item => {
        item.start = moment(`${item.start_date} 00:00`, "YYYY-MM-DD HH:mm");
        item.end = moment(`${item.end_date} 00:00`, "YYYY-MM-DD HH:mm").add(
          1,
          "days"
        );

        if (item.cuk_unavailabile_users && item.cuk_unavailabile_users.length) {
          item.title = "";

          item.cuk_unavailabile_users.forEach((user, index) => {
            let name = user.cuk_user
              ? user.user_id && user.user_id === this.props.user.id
                ? `You`
                : `${user.cuk_user.first_name} ${user.cuk_user.last_name}`
              : "";
            item.title += `${name}${
              index === item.cuk_unavailabile_users.length - 1 ? "" : ", "
            }`;
          });
        } else item.title = item.reason.replace(/<[^>]*>?/gm, "");

        item.color = "#abaaaa";
        item.textColor = "#abaaaa";
        item.allDay = true;
        item.backgroundColor = "#F2F2F4";
        item.eventStartEditable = false;
        item.isUnavailability = true;
        item.eventDurationEditable = false;
        this.arrays.push(item);
      });
      await this.setState(prevState => {
        return { events: [...prevState.events, ...this.arrays] };
      });
    }
  }

  async calendarClick(date, jsEvent, view) {
    this.setState({ event: date });

    if (date.isUnavailability)
      history.push(
        `/circle/${this.props.circle.circle_slug}/calendar/unavailable-date/edit/${date.id}`
      );
    else {
      let event = await this.props.getEvents({
        circle_id: this.props.circle.id,
        id: date.id
      });
      return this.eventDetailModal.open(event, this.props.circle);
    }
  }

  async dayClick(date, jsEvent) {}

  eventSortMenuButtonClick(flag) {
    this.setState({ eventSortMenuVisible: flag });
  }

  async onSortEventButtonClick(label, value) {
    this.setState({ eventSortLabel: label, canRender: false });
    await this.props.listEvents({
      circle_id: this.props.circle.id,
      nopaging: 1,
      event_type: value
    });

    if (
      this.props.events &&
      this.props.events.rows &&
      this.props.events.rows.length
    ) {
      this.props.events.rows.forEach((item, index) => {
        item.allDay = true;
        item.start = moment(
          `${item.start} ${item.start_time} ${item.start_time_delimeter}`,
          "YYYY-MM-DD HH:mm a"
        );
        item.end = moment(
          `${item.end} ${item.end_time} ${item.end_time_delimeter}`,
          "YYYY-MM-DD HH:mm a"
        );
      });
      this.setState({ canRender: true, events: [...this.props.events.rows] });
    }
  }

  exportCalendar(values) {
    let data = { module: "events", ...values };
    this.props.exportData(data);
  }

  handleOk() {
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        await this.exportCalendar(values);
        this.setState({ visible: false });
        this.props.form.resetFields();
      }
    });
  }

  handleCancel() {
    this.props.form.resetFields();
    this.setState({ visible: false });
  }

  showModal() {
    this.setState({ visible: true });
  }

  async onCreateEventClick() {
    await this.props.checkEventDraft({ circle_id: this.props.circle.id });

    if (this.props.eventDraft && this.props.eventDraft.id) {
      history.push(
        `/circle/${this.props.circle.circle_slug}/event/edit/${this.props.eventDraft.id}`
      );
    } else {
      if (this.selectedDate) {
        this.setState({ clickedCreate: true });
        await this.props.selectCalendarDates(this.selectedDate);
      }
      history.push(`/circle/${this.props.circle.circle_slug}/create-event`);
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <main className="main-inner-wrapper">
        <Header page="calendar" id={this.props.match.params.id} />
        <EventDetailsModal
          ref={ref => (this.eventDetailModal = ref)}
          user={this.props.user}
        />
        <div className="main-right-container">
          <Modal
            className="simple-modal"
            title="Download Information"
            visible={this.state.visible}
            onOk={this.handleOk.bind(this)}
            onCancel={this.handleCancel.bind(this)}
            cancelButtonProps={{ className: "cancel-btn" }}
            okText="Download"
          >
            <Form layout="vertical" className="simple-form">
              <Row gutter={14} type="flex">
                <Col xs={24}>
                  <FormItem label="Password">
                    {getFieldDecorator("password", {
                      rules: [
                        {
                          required: true,
                          message: "Please input the password!"
                        }
                      ]
                    })(<Input type="password" placeholder="Password" />)}
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Modal>
          <div className="circle-tabs-contents-wrapper">
            <Row gutter={16}>
              <Col xs={24} xl={16} className="grid-col-xxl-18">
                <header className="top-buttons-header">
                  {aclCheck("EventView") ? (
                    <Button
                      style={{ marginRight: "5px" }}
                      type="primary"
                      disabled={
                        this.props.circle.status === "expired" ? true : false
                      }
                      className="main-btn"
                      onClick={() => this.onCreateEventClick()}
                    >
                      <span className="icon-plus-round icon-block"></span>
                      <span className="text-block">Create new event</span>
                    </Button>
                  ) : null}
                  <Button
                    onClick={() =>
                      history.push(
                        `/circle/${this.props.circle.circle_slug}/calendar/unavailable-date`
                      )
                    }
                    className="widget-btn"
                    type="primary"
                    ghost
                  >
                    <span
                      className="icon-no-date icon-block"
                      style={{ marginRight: "10px" }}
                    ></span>
                    <span className="text-block">Manage unavailability</span>
                  </Button>
                </header>
                <div className="card-widget calendar-view-widget mb-1">
                  <header className="card-widget-header has-positioned-options">
                    <h3 className="title-text title-text-medium">Events</h3>
                  </header>
                  {this.state.loading ? (
                    <div className="loader-has-padding">
                      {" "}
                      <Loader />{" "}
                    </div>
                  ) : (
                    <div className="card-widget-content">
                      <div className="c-fullcalendar">
                        <FullCalendar
                          header={{
                            left: "prev,next today myCustomButton",
                            center: "title",
                            right: "month,listWeek"
                          }}
                          views={{
                            listWeek: { buttonText: "Week" },
                            month: { buttonText: "Month" }
                          }}
                          timeFormat="H:mm"
                          plugins={["interaction"]}
                          selectable={true}
                          fixedWeekCount={false}
                          defaultView={this.state.calendarView}
                          navLinks={true}
                          navLinkDayClick={this.dayClick}
                          editable={false}
                          eventLimit={2}
                          eventClick={this.calendarClick}
                          events={
                            aclCheck("EventView") &&
                            this.props.events &&
                            this.props.events.rows
                              ? this.state.events
                              : []
                          }
                          viewRender={(view, element) => {
                            if (view.type !== this.state.calendarView)
                              this.setState({ calendarView: view.type });
                          }}
                          showNonCurrentDates={false}
                          dateClick={info => {
                            alert("clicked " + info);
                          }}
                          select={(info, info1) => {
                            this.selectedDate = { start: info, end: info1 };
                          }}
                          unselectCancel="button"
                          unselect={() =>
                            this.props.selectCalendarDates(undefined)
                          }
                        />
                      </div>
                    </div>
                  )}
                </div>
              </Col>
              <Sidebar hideCircleOfCare={true} />
            </Row>
          </div>
        </div>
      </main>
    );
  }
}