我得到一个字符串,可以包括文本和数字数据:
例子:
"100磅""我认为173磅""73磅".
我正在寻找一种干净的方法来只从这些字符串中提取数字数据.
以下是我目前正在做的删除回复的内容:
def stripResponse(String response) {
if(response) {
def toRemove = ["lbs.", "lbs", "pounds.", "pounds", " "]
def toMod = response
for(remove in toRemove) {
toMod = toMod?.replaceAll(remove, "")
}
return toMod
}
}
Run Code Online (Sandbox Code Playgroud)
tim*_*tes 26
您可以使用findAll然后将结果转换为整数:
def extractInts( String input ) {
input.findAll( /\d+/ )*.toInteger()
}
assert extractInts( "100 pounds is 23" ) == [ 100, 23 ]
assert extractInts( "I think 173 lbs" ) == [ 173 ]
assert extractInts( "73 lbs." ) == [ 73 ]
assert extractInts( "No numbers here" ) == []
assert extractInts( "23.5 only ints" ) == [ 23, 5 ]
assert extractInts( "positive only -13" ) == [ 13 ]
Run Code Online (Sandbox Code Playgroud)
如果需要小数和负数,则可以使用更复杂的正则表达式:
def extractInts( String input ) {
input.findAll( /-?\d+\.\d*|-?\d*\.\d+|-?\d+/ )*.toDouble()
}
assert extractInts( "100 pounds is 23" ) == [ 100, 23 ]
assert extractInts( "I think 173 lbs" ) == [ 173 ]
assert extractInts( "73 lbs." ) == [ 73 ]
assert extractInts( "No numbers here" ) == []
assert extractInts( "23.5 handles float" ) == [ 23.5 ]
assert extractInts( "and negatives -13" ) == [ -13 ]
Run Code Online (Sandbox Code Playgroud)
把这个放在这里给也需要这个的人。
我只需要一个字符串中的一个数字,而不是创建新问题。
我用正则表达式做到了这一点。
def extractInt( String input ) {
return input.replaceAll("[^0-9]", "")
}
Run Code Online (Sandbox Code Playgroud)
输入this.may.have.number4.com和返回的位置4
我从上面的答案中收到错误(可能是由于我的 Jenkins 版本)-出于某种原因,我得到了这个:java.lang.UnsupportedOperationException: spread not yet supported in input.findAll(\d+)*.toInteger()----它在Jenkins 上说它已解决。
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
12677 次 |
| 最近记录: |