简体   繁体   English

如何在带有数字字符串的Java中正确使用模式

[英]How to properly use Pattern in Java with a String of numbers

I'm trying to use Pattern in Java and I'm having a problem. 我正在尝试在Java中使用Pattern ,但遇到了问题。

I want to find from a String[] that contains numbers (that I retrieved from a file) if they match another string of numbers (also from a file). 我想从包含数字(我从文件中检索到)的String[]中查找是否与另一个数字字符串(也从文件中)匹配。

Eg I have the number 1 and I want to search in a String like this: 5 10 1 8 6 3 -1 10 8 10 10 4 10 -1 10 10 10 10 9 10 -1 10 10 10 10 10 10 -1 10 10 10 10 10 10 -1 -2 . 例如,我有数字1 ,我想在这样的字符串中搜索: 5 10 1 8 6 3 -1 10 8 10 10 4 10 -1 10 10 10 10 9 10 -1 10 10 10 10 10 10 -1 10 10 10 10 10 10 -1 -2

Obviously the -1 and 10 are not what I'm locking for. 显然-110不是我要锁定的。 Is there a way to solve this? 有办法解决吗?

I can't use use Pattern.compile() with an integer. 我不能将Pattern.compile()与整数一起使用。

There are two ways: 有两种方法:

Pattern 图案

Numbers in file are seperated by spaces,so you can write pattern like this 文件中的数字用空格分隔,因此您可以这样写模式

String number = "1";
String file = "5 10 1 8 6 3 -1 10 8 10 10 4 10 -1 10 10 10 10 9 10 -1 10 10 10 10 10 10 -1 10 10 10 10 10 10 -1 -2";
file = " " + file + " "; // this is a hack to make the pattern to be right
boolean matches = Pattern.matches(".*\\s+" + number + "\\s+.*", file);
System.out.println(matches); // => true

If your remove '1' from the file, the match will be false.Because of the spaces, it will not match '-1' and '10' int the file. 如果从文件中删除'1',匹配将为false。由于空格,它将与文件中的'-1'和'10'不匹配。

ps: because of the pattern only matches the number surrounded by spaces, if the number is in the begining of the file, and there is no space in front of the number, it will not match. ps:因为该模式仅匹配带空格包围的数字,所以如果该数字位于文件开头,并且该数字前面没有空格,则它将不匹配。 So I do the hack. 因此,我做了hack。

split the file to array 将文件拆分为数组

You can split the file(also with seprator space) into array, then iterate and compare. 您可以将文件(也使用分隔符空间)拆分为数组,然后进行迭代和比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM