【问题标题】:How to identify which regex matches are prime numbers?如何识别哪些正则表达式匹配是素数?
【发布时间】:2017-01-22 23:27:33
【问题描述】:

我有一个文本文件和一个正则表达式,它可以提取整个文本中写入的所有数字。我能够匹配和提取这些数字,但我在尝试识别哪些提取的数字是素数时遇到了麻烦。

有人可以帮我吗?谢谢!

这是我的代码:

import java.util.Scanner;//Import Scanner class to read a file in the computer
import java.io.File;//Import File class to read a file in the computer
import java.io.FileNotFoundException;//Import FileNotFoundException class if case file is not found in the computer

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex2 {
    public static void main(String[] args) throws FileNotFoundException {        
        int count = 0;
        //Display each word in INPUT_TEXT
        Scanner INPUT_TEXT = new Scanner(new File("/Users/Matt/Desktop/regex2.csv"));//Create a Scanner Class and File Class to read a file from your computer.

        INPUT_TEXT.useDelimiter(" ");//Divide file into several pieces by a space  
        if (INPUT_TEXT != null) {
            System.out.println(INPUT_TEXT);
        }

        while(INPUT_TEXT.hasNext()) {
            //Read each word
            String TempString = INPUT_TEXT.next();
            //Display all numbers.Eliminate comma, e.g., 1,200 -> 1200
            String temp1 = TempString.replaceAll("[\\,]", "");//Create a String class temp1 that eliminates comma.
            String pattern1 = "[0-9]+";//Create a String class pattern1 that stores the Regular Expression to match numbers.

            Pattern r1 = Pattern.compile(pattern1);//Create Pattern class to compile pattern1.

            Matcher m1 = r1.matcher(temp1);//Match each piece with the Regular Expression

            if (m1.find()) {   
                System.out.print(m1.group() + " ");
                //System.out.println(count);
                count++;
            // if count reaches 5, reset count and print new line
            if (count == 5) {
                count = 0;
                System.out.println();
            }
        }
    }
    INPUT_TEXT.close();//Close your Scanner.
    }
}

【问题讨论】:

  • 您需要编写一个方法来确定某个输入数字是否为素数。确定整数 n 素数的唯一方法是从 1 到 \sqrt{n} 的试除法。
  • @ifly6 但如果可以使用正则表达式来完成,那不是很酷。
  • 你误解了this question。此正则表达式不检查字符串是否包含素数。问题中的代码 builds 长度为 n 的字符串(例如,*** 表示 n=3),然后使用正则表达式对其进行检查。
  • @DavidWallace 这是小事。我想要一个正则表达式来确定我的程序是否终止。 :)
  • @V1P3R 这个问题并不实际,难怪你不明白。恐怕您必须从字符串中解析一个数字,然后对其进行质数测试。看看这个问题:stackoverflow.com/questions/2385909/…

标签: java regex


【解决方案1】:

您完全误解了您链接到的帖子。看起来您有一个表示数字的字符串,并且您认为可以使用正则表达式来确定它是否为素数。这是完全不可能的。

这篇文章展示了如何通过创建一个长度为 n 的字符串来测试 n 是否为素数,并将其与仅当字符串可以分解为 2 时才匹配的正则表达式匹配或更多长度相等且长度> = 2的组。如果可以,则该数字不能是素数,因为它必须是> = 2的两个数字的乘积。这是测试素数的一种非常糟糕的方法.唯一的用途就是让一些人炫耀自己的聪明才智。

即使您确实创建了该长度的字符串,您的代码也不会工作,因为您使用的是find(),如果您的源字符串的任何子字符串匹配,它将成功。这行不通。这个技巧只有在匹配器被强制匹配整个源字符串时才有效。

【讨论】:

    【解决方案2】:

    如果您可以使用 一元 格式的数字。

    你可以参考这个link

    【讨论】:

    • 我完全理解这一点。一旦我靠近我的电脑,我会测试一下。
    • 即便如此,我不会推荐它,但对于一个有趣的项目来说“还可以”
    【解决方案3】:

    是的,我所要做的就是添加另一个“isPrime”方法。尽管我将每个匹配项添加到数组列表中,但我相信您也可以将 group(0) 解析为 Integer 并像这样测试每个值。

    这是我的代码:

    import java.util.Scanner;//Import Scanner class to read a file in the computer
    import java.io.File;//Import File class to read a file in the computer
    import java.io.FileNotFoundException;//Import FileNotFoundException class if case file is not found in the computer
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.util.*; // Import all java utilities
    
    
    public class assignmentTwo {
        public static ArrayList<Integer> nums;
    
        public static void main(String[] args) throws FileNotFoundException{
    
            int count = 0;
    
    
            //Display each word in INPUT_TEXT
            Scanner INPUT_TEXT = new Scanner(new File("/Users/Matt/Desktop/assignment2.csv"));//Create a Scanner Class and File Class to read a file from your computer.
    
    
            INPUT_TEXT.useDelimiter(" ");//Divide DemoData.txt into several pieces by a space
    
            // test to see if file was received
            if (INPUT_TEXT != null) {
    
                System.out.println(INPUT_TEXT);
    
            }
    
    
            while(INPUT_TEXT.hasNext()){
    
    
                //Read each word
                String TempString = INPUT_TEXT.next();
    
                //Display all numbers.Eliminate comma, e.g., 1,200 -> 1200
                String temp1 = TempString.replaceAll("[\\,]", "");//Create a String class temp1 that eliminates comma.
                String pattern1 = "[0-9]+";//Create a String class pattern1 that stores the Regular Expression to match numbers.
                Pattern r1 = Pattern.compile(pattern1);//Create Pattern class to compile pattern1.
                Matcher m1 = r1.matcher(temp1);//Match each piece with the Regular Expression
    
    
                // array variable
                nums = new ArrayList<Integer>();
    
                // find values that match
                if (m1.find( )) {
    
                // parse array values from string to integers
                int parsedNum = Integer.parseInt(m1.group());
                nums.add(parsedNum);
    
    
                //If a number is matched, print the number.
                System.out.print(m1.group() + " ");
    
                // increment counter when number validation is reached
                count++;
    
    
                // if count reaches 5, reset count and print new line
                if (count == 5) {
    
                count = 0;
    
                System.out.println();
    
    
    
        }
    
        // run isPrime method
         isPrime();
    
    }
    
        }
    
            INPUT_TEXT.close();//Close your Scanner.
    
        }
    
        // isPrime method to test which #s are prime
        public static int isPrime(){
    
            // finds size of array
            for(int s = 0; s < nums.size(); s++){
    
                // primeNum is true by default
                boolean primeNum = true;
    
                /* if a value from the array is divisible by any # <= array value
                    then that value is not prime */
                for (int divisor = 2; divisor <= nums.get(s) / 2; divisor++) {
                    if (nums.get(s) % divisor == 0) {
    
                        primeNum = false;
    
                    }
    
                }
                    // if value is prime, print out current value 
                    if (primeNum) {
    
                        //System.out.println();
                        System.out.print(nums.get(s) + " ");
    
                        // return array list values
                        return nums.get(s);
    
                    }
    
            }
    
            // exit status
            return 0;
        }    
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2018-10-05
      • 1970-01-01
      相关资源
      最近更新 更多