Java正则表达式,多项式的单独度和系数

时间:2023-02-01 21:47:08

I'm having trouble understanding how regex syntax works. I try to use it to read from a String the coefficients and degrees of a polynomial. I saw similar questions, but it wasn't clear enough for me. Found how to extract coefficients but when I tried to do the same for the degree I found out it beats me. For an input like: 2x^3+3x^2

我无法理解正则表达式语法的工作原理。我尝试用它从String中读取多项式的系数和度数。我看到了类似的问题,但对我来说还不够清楚。找到了如何提取系数,但当我尝试做同样的程度时,我发现它击败了我。输入如:2x ^ 3 + 3x ^ 2

        //for coeff
        String[] coef = str.split("x\\^\\d+\\+?");
        for (String part : coef)
        {
            System.out.println(part);
         }

        //for degree
        String[] degree = str.split("+\\+?\\d");
        for (String part : degree)
        {
            System.out.println(part);
         }

Already consulted this.

已经咨询过这个。

4 个解决方案

#1


4  

Rather than using 2 different regex and doing 2 split operations I suggest using a match with a single regex:

我建议使用匹配单个正则表达式而不是使用2个不同的正则表达式并执行2个拆分操作:

Pattern p = Pattern.compile( "(-?\\b\\d+)[xX]\\^(-?\\d+\\b)" );

You can then use Matcher.find() to get both coef (matched group 1) and degree (matched group 2).

然后,您可以使用Matcher.find()来获得coef(匹配的组1)和程度(匹配的组2)。

RegEx Demo


Code:

String input = "2x^3-3x^-2";
Pattern p = Pattern.compile( "(-?\\b\\d+)[xX]\\^(-?\\d+\\b)" );
Matcher m = p.matcher( input );
while (m.find()) {
    System.out.println("Coef: " + m.group(1));
    System.out.println("Degree: " + m.group(2));
}

#2


2  

String monomPattern = "((-?\\d+(?=x))?(-?[xX])(\\^(-?\\d+))?)|((-?)[xX])|(-?\\d+)";

This should work if you don't have any white spaces. If you have, simply call the replaceAll("\s+","") method for strings. (this method do not change the original String, so you have to assign it to itself)

如果您没有任何空格,这应该有用。如果有,只需为字符串调用replaceAll(“\ s +”,“”)方法即可。 (此方法不会更改原始字符串,因此您必须将其分配给自身)

e.g. textField = textField.replaceAll("\\s+","");

ims

#3


1  

Just split your input according to the below regex for getting degree values.

只需根据以下正则表达式分割您的输入以获取度数值。

String s[] = str.split("\\+?\\d+x\\^");

DEMO

#4


0  

Try this REGEX:

试试这个REGEX:

  /*GROUP 1 = sign (optional for positive numbers) -> -3x; (+3x, 3x)
    GROUP 2 = digit (optional if it's -1 or 1) -> (-1x, -x); (1x, x)
    GROUP 3 = term with x in its structure -> 3x, -5x^2
    GROUP 4 = exponent structure (^exponent) (optional if it's 1) -> (4x^1, 4x); 4x^-1; 2x^3
    The REGEX supports integer and real values: 4.5, 4., 0.25, .25 etc.
    The REGEX does not support fractions: 3/4, 6/4 (use the real value: 0.75, 1.25)
     */
    String monomialPattern = "([-+]?)(\\d*\\.?\\d*)?([xX](\\^-?\\d*\\.?\\d*)?)?"

    Polynomial parsedPolynomial = new Polynomial();

    // double backslash stands for \s which represents a white space
    // + means that all the white spaces from the String will be replaced with ""
    input = input.replaceAll("\\s+", "");

    // Converts the REGEX string into a valid pattern
    Pattern pattern = Pattern.compile(monomialPattern);

    // Creates an object which will test the pattern against the input
    Matcher matcher = pattern.matcher(input);

You can exercise regular expressions here: REGEXR

你可以在这里运用正则表达式:REGEXR

#1


4  

Rather than using 2 different regex and doing 2 split operations I suggest using a match with a single regex:

我建议使用匹配单个正则表达式而不是使用2个不同的正则表达式并执行2个拆分操作:

Pattern p = Pattern.compile( "(-?\\b\\d+)[xX]\\^(-?\\d+\\b)" );

You can then use Matcher.find() to get both coef (matched group 1) and degree (matched group 2).

然后,您可以使用Matcher.find()来获得coef(匹配的组1)和程度(匹配的组2)。

RegEx Demo


Code:

String input = "2x^3-3x^-2";
Pattern p = Pattern.compile( "(-?\\b\\d+)[xX]\\^(-?\\d+\\b)" );
Matcher m = p.matcher( input );
while (m.find()) {
    System.out.println("Coef: " + m.group(1));
    System.out.println("Degree: " + m.group(2));
}

#2


2  

String monomPattern = "((-?\\d+(?=x))?(-?[xX])(\\^(-?\\d+))?)|((-?)[xX])|(-?\\d+)";

This should work if you don't have any white spaces. If you have, simply call the replaceAll("\s+","") method for strings. (this method do not change the original String, so you have to assign it to itself)

如果您没有任何空格,这应该有用。如果有,只需为字符串调用replaceAll(“\ s +”,“”)方法即可。 (此方法不会更改原始字符串,因此您必须将其分配给自身)

e.g. textField = textField.replaceAll("\\s+","");

ims

#3


1  

Just split your input according to the below regex for getting degree values.

只需根据以下正则表达式分割您的输入以获取度数值。

String s[] = str.split("\\+?\\d+x\\^");

DEMO

#4


0  

Try this REGEX:

试试这个REGEX:

  /*GROUP 1 = sign (optional for positive numbers) -> -3x; (+3x, 3x)
    GROUP 2 = digit (optional if it's -1 or 1) -> (-1x, -x); (1x, x)
    GROUP 3 = term with x in its structure -> 3x, -5x^2
    GROUP 4 = exponent structure (^exponent) (optional if it's 1) -> (4x^1, 4x); 4x^-1; 2x^3
    The REGEX supports integer and real values: 4.5, 4., 0.25, .25 etc.
    The REGEX does not support fractions: 3/4, 6/4 (use the real value: 0.75, 1.25)
     */
    String monomialPattern = "([-+]?)(\\d*\\.?\\d*)?([xX](\\^-?\\d*\\.?\\d*)?)?"

    Polynomial parsedPolynomial = new Polynomial();

    // double backslash stands for \s which represents a white space
    // + means that all the white spaces from the String will be replaced with ""
    input = input.replaceAll("\\s+", "");

    // Converts the REGEX string into a valid pattern
    Pattern pattern = Pattern.compile(monomialPattern);

    // Creates an object which will test the pattern against the input
    Matcher matcher = pattern.matcher(input);

You can exercise regular expressions here: REGEXR

你可以在这里运用正则表达式:REGEXR