首页 \ 问答 \ Java正则表达式String.matches工作不一致(Java regex String.matches working inconsistently)

Java正则表达式String.matches工作不一致(Java regex String.matches working inconsistently)

我有一个正则表达式来检查一个字符串是否是一个数字。 格式的千位分隔符是一个空格,小数点分隔符是一个点。 小数点后部分是可选的。

问题是,在某些时候String.matches()函数停止按预期工作。 之前的工作,不再工作。

例如,JUnit代码:

import junit.framework.Assert;
import org.junit.Test;

public class RegExTest {

    @Test
    public void testThousandSeperatorRegex()
    {
        String regEx = "([0-9]{1,3}( [0-9]{3})*(\\.[0-9]+)?|\\.[0-9]+)";
        Assert.assertEquals(true, "1".matches(regEx));
        Assert.assertEquals(true, "10".matches(regEx));
        Assert.assertEquals(true, "100".matches(regEx));
        Assert.assertEquals(true, "1 000".matches(regEx));
        Assert.assertEquals(true, "10 000".matches(regEx));
        Assert.assertEquals(true, "100 000".matches(regEx));
        Assert.assertEquals(true, "1 000 000".matches(regEx));
        Assert.assertEquals(true, "10 000 000".matches(regEx));
        Assert.assertEquals(false, "10000.56".matches(regEx));
        Assert.assertEquals(true, "8 734".matches(regEx));
    }
}

“8 734”的最后一行失败。 当我用“1 000”代替它时,它仍然会失败。 最后,同一次运行中的相同代码在第四行断言中传递,但最后一次失败(新代码保存!)。 但有时候,一切都开始按预期工作,直到......再次失败。 所以我想这将很难重现我的问题。 也许还有一些我做错的事情我没有注意到,因此没有被描述,但我试图尽可能地说明问题。 这个让我很困惑。 String.matches()是否有内存或什么?

正则表达式可能有问题吗? 我正在跳过^$因为String.matches无论如何都可以在整个字符串上工作。 我已经尝试过java.util.regex和jregex包,问题依然存在。

我正在使用JDK 6u31。

任何想法赞赏。

UPD:好的,在发布这个Q之后,代码开始工作并且至今没有失败。 也许这是与我有关的事情,但自从上周以来,这一直困扰着我,我已经能够一次又一次地复制它。 我会继续使用我的代码,如果它能继续工作,我会解决这个问题。 此外,我会尝试确定究竟是什么造成了这个问题。 同时,如果有人遇到同样的问题,请分享您的知识。 否则,这看起来像一个问题,可以通过知识解决,而不是通过调试。 为了捍卫自己的愚蠢,我可以说我已经编程了很多年,这是论坛上的第一篇文章:)。 到现在为止,我能够通过调试,阅读文档和搜索其他Q的论坛来解决我的问题。


I have a regex which checks if a string is a number. The format's thousand separator is a white space, decimal separator is a dot. After-decimal part is optional.

The issue is that at some point String.matches() function stops working as expected. What worked before, does not work anymore.

For example, JUnit code:

import junit.framework.Assert;
import org.junit.Test;

public class RegExTest {

    @Test
    public void testThousandSeperatorRegex()
    {
        String regEx = "([0-9]{1,3}( [0-9]{3})*(\\.[0-9]+)?|\\.[0-9]+)";
        Assert.assertEquals(true, "1".matches(regEx));
        Assert.assertEquals(true, "10".matches(regEx));
        Assert.assertEquals(true, "100".matches(regEx));
        Assert.assertEquals(true, "1 000".matches(regEx));
        Assert.assertEquals(true, "10 000".matches(regEx));
        Assert.assertEquals(true, "100 000".matches(regEx));
        Assert.assertEquals(true, "1 000 000".matches(regEx));
        Assert.assertEquals(true, "10 000 000".matches(regEx));
        Assert.assertEquals(false, "10000.56".matches(regEx));
        Assert.assertEquals(true, "8 734".matches(regEx));
    }
}

The last line with "8 734" fails. When I replace it with "1 000" it continues to fail. Eventually, the same code at the same run passes in the 4th line of assertions, but fails in the last (the new code is saved!). But there are times when everything starts working just as expected until.. start failing again. So I suppose that it will be hard to reproduce my issue. Maybe there are something else that I'm doing wrong which I haven't noticed and thus described, but I tried to make it as plain as possible. This one confuses me a lot. Does String.matches() has a memory or what?

Could there be something wrong with the regular expression? I'm skipping ^$ as String.matches works on whole string anyway. I have tried java.util.regex and jregex packages, the issue persisted.

I'm using JDK 6u31.

Any ideas appreciated.

UPD: ok, after posting this Q the code started to work and hasn't fail so far. Maybe it was something with me, but this has bothered me since last week and I have been able to replicate it again and again. I will continue with my piece of code and if it will continue to work I will close this issue. Also I will try to determine what exactly caused the problem. Meanwhile, if there are someone out there who has encountered the same issue, please share your knowledge. Otherwise, this looks like an issue that can be solved by knowledge, not by debugging. To defend myself from stupidity I can say I have been programming for many years and this is the 1st ever post in forums :). Until now I was able to solve my problems with debugging, reading docs and searching forums of other Qs.


原文:https://stackoverflow.com/questions/10126347
更新时间:2023-09-13 12:09

相关问答

更多
  • 根据需要使用的布局超过2个: FrameLayout:用作视图框架以显示单个对象的布局。 RelativeLayout:允许您指定子对象相对于彼此的位置(子B的左侧的子A)或父对象的位置(对齐到父对象的顶部)。 LinearLayout:将子项组织为单个水平或垂直行的布局。 如果窗口的长度超过屏幕的长度,它会创建一个滚动条。 TableLayout:具有任意行数和列数的表格布局,每个单元格包含您选择的小部件。 行调整大小以适合最大的列。 单元格边框不可见。 There are more then 2 lay ...
  • 试试这个代码并告诉我它是否有效。 删除布局的膨胀 import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; public class teamCreateScreen extends Activity { int i=0; @Override protected ...
  • 我猜你在onCreate中尝试过setRetainInstance(true)吗? 尽管如此,如果不削减它,我认为你将不得不以某种方式持久化状态,无论是数据库还是包含模型数据的文件。 然后在onCreate中检查数据库/文件并相应地增加布局。 I guess you did try setRetainInstance(true) in onCreate? Nonetheless if that does not cut it I think you will have to persist the stat ...
  • 没有XML很难看到,但通常当你调用inflate你应该传递一个根视图,否则你在XML布局中指定的任何布局参数都将丢失。 试试吧,也许吧? inflater = LayoutInflater.from(MainActivity.this); RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout); View inflated = inflater.inflate(R.layout.layout, layout, false); lay ...
  • 但有没有办法用SimpleCursorAdapter进行简单的自定义? 就像BaseAdapter一样,您可以扩展CursorAdapter或SimpleCursorAdapter来进行自定义。 例如。 我有一个数据库,我想查询它并将结果返回到具有交替行布局的ListView。 如果您只是替换行颜色之类的小事,则可以简单地覆盖bindView()并检查if(cursor.getPosition() % 2 == 0) (或== 1 )来设置适当的背景颜色。 如果在每个布局中使用不同类型或数量的视图,则需要覆 ...
  • 我只用一个更改复制了你的代码:我删除了 tools:context="${relativePackage}.${activityClass}" 来自activity_verbs,它对我来说就像一个魅力: 我将带有代码的测试项目上传到DropBox,随时可以下载: https ://www.dropbox.com/s/8fcdab3rmx8zb57/ElaPinkSO.zip?dl = 0 PS结构很好的问题,干得好! I copied your code with only one change: I ...
  • 我只需要添加 app:layout_behavior="@string/appbar_scrolling_view_behavior" 到线性布局 I just had to add app:layout_behavior="@string/appbar_scrolling_view_behavior" to the linear layout
  • 所以,我最终要做的是创建一个BaseViewHolder.class ,创建扩展这个BaseViewHolder其他ViewHolder类,这样我的RecyclerView.Adapter看起来仍然很干净,因为我最终得到了像ViewHolder这样的ViewHolder : public class BaseVH extends RecyclerView.ViewHolder { private ViewDataBinding mBinding; public BaseVH(ViewDat ...
  • 这里有几个快速指南: Android Layouts往往比你通常期望的嵌套得更深。 您经常会得到“空”布局,只占用空间,以便其他元素正确布局。 无论何时将文本对齐到特定边缘,RelativeLayout都是您的朋友。 使用填充设置将文本“稍微远离”边缘。 重力对齐TextView或按钮中的文本。 再看看你的图,我是这样转载的: 从占据整个屏幕的相对布局('fill_content')开始。 通过锚定到顶部和底部来放入“短文本”和“更多文本”。 将一个零宽度的项目放置在屏幕中间的一个点上,其属性为“cente ...
  • getId()将返回布局中顶级View的id。 因此,例如,如果你在my_layout.xml中有这样的布局文件:

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)