使用Ruby正则表达式解析数字

时间:2021-12-11 01:43:04

I have a situation where I need to grab a large number from a string. The two cases I'm working with are:

我有一种情况需要从字符串中获取大量数字。我正在处理的两个案例是:

1) when the number is made up of only numbers, like 265038960

1)当数字仅由数字组成时,如265038960

2) When the number has a letter appended to it, like 69235M

2)当数字附加一个字母时,如69235M

I've been using the regex pattern

我一直在使用正则表达式模式

(\d.+)[A-Z]

This works for the second case and grabs '69235' without the 'M', but breaks on the first case where a letter is not found.

这适用于第二种情况并且在没有“M”的情况下抓取“69235”,但在第一种没有找到字母的情况下中断。

How can I use a condition within the regex to only parse out the number whether or not a letter is present at the end of the string?

如何在正则表达式中使用条件来仅解析数字是否在字符串末尾出现字母?

1 个解决方案

#1


1  

(\d+[A-Z]?)       # capture any number of digits, together with 0 or 1 uppercase letter

It's not clear if you want to capture the letter or not. In the case you want to dispose of the letter:

目前尚不清楚你是否想要捕获这封信。如果你想处理这封信:

(\d+)[A-Z]?       # capture any number of digits, followed by 0 or 1 uppercase letter

Look at example

看一下例子

#1


1  

(\d+[A-Z]?)       # capture any number of digits, together with 0 or 1 uppercase letter

It's not clear if you want to capture the letter or not. In the case you want to dispose of the letter:

目前尚不清楚你是否想要捕获这封信。如果你想处理这封信:

(\d+)[A-Z]?       # capture any number of digits, followed by 0 or 1 uppercase letter

Look at example

看一下例子