Using Regular Expressions to Extract a Value in Java

前端 未结 13 1257
失恋的感觉
失恋的感觉 2020-11-22 13:08

I have several strings in the rough form:

[some text] [some number] [some more text]

I want to extract the text in [some number] using the

13条回答
  •  萌比男神i
    2020-11-22 13:23

    Allain basically has the java code, so you can use that. However, his expression only matches if your numbers are only preceded by a stream of word characters.

    "(\\d+)"
    

    should be able to find the first string of digits. You don't need to specify what's before it, if you're sure that it's going to be the first string of digits. Likewise, there is no use to specify what's after it, unless you want that. If you just want the number, and are sure that it will be the first string of one or more digits then that's all you need.

    If you expect it to be offset by spaces, it will make it even more distinct to specify

    "\\s+(\\d+)\\s+"
    

    might be better.

    If you need all three parts, this will do:

    "(\\D+)(\\d+)(.*)"
    

    EDIT The Expressions given by Allain and Jack suggest that you need to specify some subset of non-digits in order to capture digits. If you tell the regex engine you're looking for \d then it's going to ignore everything before the digits. If J or A's expression fits your pattern, then the whole match equals the input string. And there's no reason to specify it. It probably slows a clean match down, if it isn't totally ignored.

提交回复
热议问题