首页 \ 问答 \ 仅从String中提取数字(Extract only the numbers from String)

仅从String中提取数字(Extract only the numbers from String)

我需要一个给出以下字符串的正则表达式:“12.123.123 / 1234-11”,“12.123123123411”或“1123123 / 1234-11”。 我只能提取数字(12123123123411);

Pattern padrao = Pattern.compile("\d+");
Matcher matcher = padrao.matcher("12.123.123/1234-11");
while (matcher.find()) {
    System.out.println(matcher.group());
}
//output:12,123,123,1234,11,
//I need: 121231234123411

谁能帮我?


I need a Regex that given the following Strings: "12.123.123/1234-11", "12.123123123411" or "1123123/1234-11". I could extract only the numbers(12123123123411);

Pattern padrao = Pattern.compile("\d+");
Matcher matcher = padrao.matcher("12.123.123/1234-11");
while (matcher.find()) {
    System.out.println(matcher.group());
}
//output:12,123,123,1234,11,
//I need: 121231234123411

Can anyone help me?


原文:https://stackoverflow.com/questions/18147886
更新时间:2019-12-13 08:36

最满意答案

更好的方法是使用String#replaceAll(regex, replacement)方法替换除数字之外的所有字符(如您所见,该方法需要使用正则表达式进行替换):

String str = "12.123.123/1234-11";
String digits = str.replaceAll("\\D", "");

\\D匹配非数字字符。 相当于[^0-9] 。 请注意,您需要在Java正则表达式引擎上转义\D


如果您对使用Matcher#group()方法有限制,那么每次找到它们时都必须构建一个StringBuilder实例,附加数字:

String str = "12.123.123/1234-11";
StringBuilder digits = new StringBuilder();

Matcher matcher = Pattern.compile("\\d+").matcher(str);

while (matcher.find()) {
    digits.append(matcher.group());
}

System.out.println(digits);

A better way would be use String#replaceAll(regex, replacement) method to replace all characters except digits (As you see, the method takes a regex for replacing):

String str = "12.123.123/1234-11";
String digits = str.replaceAll("\\D", "");

\\D matches non-digit characters. Equivalent to [^0-9]. Note that, you need to escape the \D on Java regex engine.


If you have restriction for using Matcher#group() method, then you would have to build a StringBuilder instance, appending digits, everytime they are found:

String str = "12.123.123/1234-11";
StringBuilder digits = new StringBuilder();

Matcher matcher = Pattern.compile("\\d+").matcher(str);

while (matcher.find()) {
    digits.append(matcher.group());
}

System.out.println(digits);
2013-08-21

相关问答

更多

打印json对象时出现意外的标记L使用高级rest chrome(Unexpected Token L when printing a json object Using advanced rest chrome)

确定如果错误发生在客户端中,那么您将返回错误形成的JSON值,因此您返回类似的内容: { id: 13, name: "Name"}Login invalid然后L { id: 13, name: "Name"}Login invalid的第一个字符JSON语法。 这是因为你在响应中写了getFromDatabase out.print(JObject.toString());方法中的json字符串out.print(JObject.toString()); 并在方法调用之后添加到响应中,字符串

如果Textbox为空,则ASP.NET GridView不会从更改SqlDataSource.SelectCommand填充(ASP.NET GridView won't populate from changing SqlDataSource.SelectCommand if Textbox is empty)

通过向其上定义的Title属性添加一个默认值NULL来修改您的SqlDataSource,这应该可以解决问题。 你不需要标签,我还是不懂标签。 <asp:SqlDataSource runat="server" ID="SqlDataSourceSearchResults" ConnectionString='<%$ ConnectionStrings:DefaultConnection %>' SelectCommand=""> <SelectParameters> <

具有可变儿童深度的d3.nest(d3.nest with variable children depth)

由于d3.nest使您在调用nest.entries之前提前注册嵌套键,因此无法通过nest.entries指定所有内容来使用可变数量的级别进行嵌套。 可能有用的一件事是递归使用nest.rollup函数来控制每个级别的值是什么样的。 在rollup内部,您可以决定每个条目元素是否应该是包含下一级详细信息的新d3.nest ,或者它是否应该是叶节点。 这是一个粗略的裂缝(假设level1将始终存在): function rollupFn(group) { var leaves = [],

观看os 2.0 Beta:未收到通知(Watch os 2.0 Beta: Not Receiving notifications)

我自己解决了。 显然问题是iOS9和Watch OS 2的beta版本不再匹配了。 我刚刚将我的iOS升级到Beta 5,但忘了做WatchOS,因为我不习惯这个过程。 在今天同步测试版之后,iOS和WatchOS之间的连接很顺利:) 我第一次也可以在手表上正确调试XCode! I solved it myself. Apperently the problem was the beta versions of iOS9 and Watch OS 2 not matching up anymor

是否有适用于XP或Windows 2008 R2的.NET 4.0 WPF Performance Suite?(Is there a WPF Performance Suite for .NET 4.0 for XP or Windows 2008 R2? [closed])

适用于Windows 7和.NET Framework 4的Windows SDK 7.1版包括Performance Suite,并兼容这些版本的Windows和.Net 4.请参阅Windows SDK发布博客条目 Version 7.1 of the Windows SDK for Windows 7 and .NET Framework 4 includes the Performance Suite and is compatible with both these versions

不同的PPT模板在同一个宏上作出不同的反应(Different PPT templates reacting different on the same macros)

您的脚注错位,因为一个演示文稿中的默认文本设置与另一个演示文稿中的默认文本设置不同; 在这种情况下自动调整设置。 ' in this section of your FOOTNOTE routine: With .TextFrame ' Add this next line and it will work as expected .AutoSize = ppAutoSizeNone .TextRange.Text = "Note: " & vbCrLf & "Sourc

jsPlumb draggable element javascript函数(jsPlumb draggable element javascript function)

你错过了jsPlumb.setContainer($("body")); https://jsfiddle.net/mkaran/mLthybzo/ https://jsplumbtoolkit.com/community/doc/home 编辑:你的例子的小提琴https://jsfiddle.net/mkaran/aof6mq34/ You are missing the jsPlumb.setContainer($("body")); https://jsfiddle.net/mkaran

MVC4:ViewModel(带有radiobuttonlist)在HttpPost之后为空(MVC4: ViewModel (with radiobuttonlist) is empty after HttpPost)

我没有看到表单有如下ID的映射: @Html.HiddenFor(model => model.Id) 每个内部问题集合也应该具有Id,以便与表单一起发布。 因此,对于您可以拥有的每个问题,在表单的foreach循环中: @Html.HiddenFor(model => item.Question.Id) 该模型还具有MultipleChoiceQuestion类型的集合。 对于模型绑定到集合,集合元素的名称应具有带有序数字的name属性,如本文http://haacked.com/arch

相关文章

更多

最新问答

更多
  • jsPlumb draggable element javascript函数(jsPlumb draggable element javascript function)
  • MVC4:ViewModel(带有radiobuttonlist)在HttpPost之后为空(MVC4: ViewModel (with radiobuttonlist) is empty after HttpPost)
  • 如何在同一帐户上设置“Dev repo”(在prod和团队之间)(How to set up a “Dev repo” (between the prod and the team) on the same account)
  • 如何在tcl中将eth0配置为发送方udp端口(how to configure eth0 as a sender udp port in tcl)
  • 在main方法中进行更改后传递给构造函数的TreeMap实例的行为是什么(What is the behavior of a TreeMap instance passed into a constructor following changes in main method)
  • 在这个的一些属性不同的颜色(Different color in some properties of this)
  • CURL没有返回任何内容(CURL Not returning anything)
  • MVC5注入依赖于城堡windsor的视图(MVC5 injecting dependency on a view with castle windsor)
  • CakePHP AJAX-Call:发生错误:未定义(CakePHP AJAX-Call: An error occured: undefined)
  • 如何用.aidl扩展名创建文件?(how to create a file with .aidl extension?)
  • 无法获得全尺寸动态WordPress灯箱图像显示(Cannot get full size dynamic WordPress lightbox image to display)
  • 使用Jsoup删除元素不起作用(Removing Element with Jsoup doesn't work)
  • 交叉编译ARM的MongoDB C ++驱动程序。(Cross compiling MongoDB C++ driver for ARM. Cannot find Boost Libraries)
  • ProgressDialog没有关闭(ProgressDialog not closing)
  • 单元测试DB中的JPA插入(Unit testing JPA insertion in the DB)
  • 点击谷歌服务对话框中的更新按钮(Click on update button in check google service dialog)
  • 适用于PhoneGap Build的iOS“缺少必需的57x57图标”(“Missing required 57x57 icon” for iOS on PhoneGap Build)
  • MVC ckeditor post编辑器值内联(MVC ckeditor post editor value inline)
  • Angular 2 Pipe - 无法读取未定义的属性'toString'(Angular 2 Pipe - Cannot read property 'toString' of undefined)
  • 安装引导加载程序(Installing bootloaders)
  • 用于确定最终如何包含头文件的工具(Tool to figure out how a header file is eventually being included)
  • 在将字符串转换为int [duplicate]之前检查字符串是否不是数字(Check if string is not a number before converting it to a int [duplicate])
  • 从脚本构建db2数据库以进行构建验证的工具?(Tools to build db2 database from scripts for build verification?)
  • 在偏移之后向FileOutputStream写一个数字(Write a number to FileOutputStream after an offset)
  • Javascript RegEx仅限数字(无特殊字符)(Javascript RegEx for Numbers Only (no special characters))
  • 我可以在PHP的Linux服务器上运行新的COM(“WScript.Shell”)(Can I run new COM(“WScript.Shell”) on linux servers in PHP)
  • 在Backbone.js中放置与视图不直接相关的代码(例如广告,分析等)的位置?(Where to place code not directly related to a view (such as ads, analytics etc) in Backbone.js?)
  • 适用于Mac和PC的一般开发人员必备软件综合列表[关闭](Comprehensive List of Essential Software for General Developers on Mac and PC [closed])
  • 将语言文本转换为模型(Transformation Language Text to Model)
  • 在控制器中的两个方法之间共享变量?(Sharing variables between two methods in a controller?)