The meaning of the regular expression ¥d.+?yen

Asked 2 years ago, Updated 2 years ago, 103 views

I am currently studying Java regular expressions through the website.
"I don't understand the meaning of the part written ""¥d.+?yen"" below."Could you please let me know what pattern it means to match the target string?
■ Source

String str = "Tomato is 100yen, Lemon is 80yen.";
String regex="¥d.+?yen";
Pattern p = Pattern.compile(regex);

Matcher m=p.matcher(str);
if(m.find()){
  System.out.println("Matched";
}

java regular-expression

2022-09-30 21:21

2 Answers

The \\ attached to your question is also a circle symbol, so please use \\ when you are actually trying.(If you copy, it may look garbled, but don't panic and choose the correct one.)

Now, if you look at String regex="\\d.+?yen", removing the escape as a Java string means passing the \d.<

If you look at it in order,

  • \d—Matches a digit in regular expression, one decimal character.
  • .—The most commonly used meta-character in regular expressions, but matches any character other than a new line (*).
  • +?—Indicates that the quantified meta-character repeats the previous element 最短one or more minimum matches.
  • yen—Indicates that each matches the character itself.

When applied to the str you suggested, the first find() is as follows:
- \d:1
- .+?:00
- yen:ye
n

Therefore, if you add a code that displays the entire match, you should know that 100yen is a match.

By the way, removing ? after + in the pattern will be the longest match, so 100yen, Lemon is 80yen will match on the first find().

Roughly speaking, the original regular expression pattern is a pattern that looks for "starting with a number and ending with the most recent yen.

There is also an option to instruct (*). to match line breaks as well.


2022-09-30 21:21

Regular expressions are described in the java.util.regex.pattern API reference, where \\d is a number (same as [0-9], . is any single character, and +? is a single iteration (quantum of minimum matches), so check it out first.

However, there is no detailed description of the reference as if the longest match quantum, the shortest match quantum, and the greedy number quantum were common sense.><

If you search for these differences, for example, on the next page, you will find a page that explains them in detail.
Maximum Match Quantum/Minimum Match Quantum/Greedy Number Quantum


2022-09-30 21:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.