如果不是所有数字,我如何拆分字符串标记?

时间:2017-02-13 03:25:40

标签: ruby regex split

我想在数组中分割标记,如果它们的形式为“数字,点(”。“),然后是非数字”。如果令牌的形式为:“number,dot,number”,我不想拆分它。我认为这会做到这一点

tokens.flat_map {|o| o.scan(/^\d+\.|[a-z]+/i) }

该表达式适用于这种情况:

tokens = ["44.WORD"]
tokens.flat_map {|o| o.scan(/^\d+\.|[a-z]+/i) }
# => ["44.", "WORD"] 

但表达似乎切断了令牌,如下所示:

tokens = ["72.9"]
tokens.flat_map {|o| o.scan(/^\d+\.|[a-z]+/i) }
# => ["72."] 

如何调整我的正则表达式,以便如果令牌是一个数字,一个点和一个数字,我保持原样并将其分成两部分?

2 个答案:

答案 0 :(得分:0)

试试这个

tokens.flat_map { |token| token =~ /[a-z]/i ? token.split('.') : token }

这不会调整你的正则表达式,但有时候使用Ruby更容易,而不是把所有内容都塞进正则表达式。并且通常也更具可读性。

答案 1 :(得分:0)

由于您已明确定义了拆分位置的概念,因此请使用IDField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evnt) { if (evnt.getKeyCode() == KeyEvent.VK_ENTER) { try { String query = "select * from employee where IDNo = ?"; PreparedStatement pst = connection.prepareStatement(query); pst.setString(1, IDField.getText()); ResultSet rs = pst.executeQuery(); table.setModel(DbUtils.resultSetToTableModel(rs)); int count = 0; while (rs.next()) { count += 1; } if (count == 1) { JOptionPane.showMessageDialog(null, "ID Verified!"); IDField.setText(null); } else { JOptionPane.showMessageDialog(null, "ID was'nt recognize, Try again..."); } rs.close(); pst.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } } } }); 代替SELECT * FROM Activity Inner UserActivity on UserActivity.activity_id = Activity.activity_id Inner Join User on UserActivity.user_id = User.user_id ;

activity_name  activity_time   user_id   email           first_name   last_name
Reading        00:00:15        10001     btv@gmail.com   Mike         Porter
Share          00:01:10        10765     ud@gmail.com    Jamie        Hollands
Like           23:15:00        15761     rsv@gmail.com   Ragav        Taylor
Tweet          07:59:01        17001     trv@gmail.com   Julie        Smith