Java Regular Expression

I am not very familiar with regular expressions.
I need help for the following regular exceptions:
1. The line begins with an alpha word, and then any alpha or number follows. e.g. Abc January 20 to December 15
2. String for decimal number. e.g. 450 122 240.00
3. Also, to check if String contains any pattern, for example "Page 2 of 20"

Thanks.

+4
source share
3 answers
// 1. String start with alpha word and then followed by // any aplha or number. eg Abc 20 Jan to 15 Dec // One or more alpha-characters, followed by a space, // followed by some alpha-numeric character, followed by what ever Pattern p = Pattern.compile("\\p{Alpha}+ \\p{Alnum}.*"); for (String s : new String[] {"Abc 20 Jan to 15 Dec", "hello world", "123 abc"}) System.out.println(s + " matches: " + p.matcher(s).matches()); // 2. String for a decimal number. eg 450,122,224.00 p = Pattern.compile( "\\p{Digit}+(\\.\\p{Digit})?|" + // w/o thousand seps. "\\p{Digit}{1,3}(,\\p{Digit}{3})*\\.\\p{Digit}+"); // w/ thousand seps. for (String s : new String[] { "450", "122", "224.00", "450,122,224.00", "0.0.3" }) System.out.println(s + " matches: " + p.matcher(s).matches()); // 3. Also to check if String contain any pattern like 'Page 2 of 20' // "Page" followed by one or more digits, followed by "of" // followed by one or more digits. p = Pattern.compile("Page \\p{Digit}+ of \\p{Digit}+"); for (String s : new String[] {"Page 2 of 20", "Page 2 of X"}) System.out.println(s + " matches: " + p.matcher(s).matches()); 

Conclusion:

 Abc 20 Jan to 15 Dec matches: true hello world matches: true 123 abc matches: false 450 matches: true 122 matches: true 224.00 matches: true 450,122,224.00 matches: true 0.0.3 matches: false Page 2 of 20 matches: true Page 2 of X matches: false 
+3
source

1 I'm not sure what you mean here. A word at the beginning, followed by any number of words and numbers? Try the following:

 ^[a-zA-Z]+(\s+([a-zA-Z]+|\d+))+ 

2 Just a decimal number will be

 \d+(\.\d+)? 

Getting commas there:

 \d{1,3}(,\d{3})*(\.\d+)? 

3 Use

 Page \d+ of \d+ 
0
source

1.) /[AZ][az]*(\s([\d]+)|\s([A-Za-z]+))+/

[AZ][az]* is a headword

\s([\d]+) is the number prefix representing the (white) space

\s([A-Za-z]+) , which is a prefix word, is a (white) space

2.) / ( /(\d{1,3})(,(\d{3}))*(.(\d{2}))/ ( )(((( /(\d{1,3})(,(\d{3}))*(.(\d{2}))/ ))) /(\d{1,3})(,(\d{3}))*(.(\d{2}))/

(\d{1,3}) is a number from 1 to 3 digits

(,(\d{3}))* is 0 or more three-digit numbers with a comma prefix

(.(\d{2})) is a two-digit decimal character

3.) /Page (\d+) of (\d+)/

(\d+) is one or more digits

When writing this (or any regular expression) I like to use this tool

0
source

Source: https://habr.com/ru/post/1315075/


All Articles