Reputation: 1387
I am not a Java developer but I am interfacing with a Java system. Please help me with a regular expression that would detect all numbers starting with with 25678 or 25677.
For example in rails would be:
^(25677|25678)
Sample input is 256776582036
an 256782405036
Upvotes: 1
Views: 3186
Reputation: 1937
^(25678|25677)
or
^2567[78]
if you do ^(25678|25677)[0-9]*
it Guarantees that the others are all numbers and not other characters.
Should do the trick for you...Would look for either number and then any number after
Upvotes: 3
Reputation: 234807
The regex syntax of Java is pretty close to that of rails, especially for something this simple. The trick is in using the correct API calls. If you need to do more than one search, it's worthwhile to compile the pattern once and reuse it. Something like this should work (mixed Java and pseudocode):
Pattern p = Pattern.compile("^2567[78]");
for each string s:
if (p.matcher(s).find()) {
// string starts with 25677 or 25678
} else {
// string starts with something else
}
}
If it's a one-shot deal, then you can simplify all this by changing the pattern to cover the entire string:
if (someString.matches("2567[78].*")) {
// string starts with 25677 or 25678
}
The matches()
method tests whether the entire string matches the pattern; hence the leading ^
anchor is unnecessary but the trailing .*
is needed.
If you need to account for an optional leading +
(as you indicated in a comment to another answer), just include +?
at the start of the pattern (or after the ^
if that's used).
Upvotes: 0
Reputation: 37023
Try something like:
String number = ...;
if (number.matches("^2567[78].*$")) {
//yes it starts with your number
}
Regex ^2567[78].*$
Means:
Number starts with 2567 followed by either 7 or 8 and then followed by any character.
If you need just numbers after say 25677, then regex should be ^2567[78]\\d*$
which means followed by 0 or n numbers after your matching string in begining.
Upvotes: 0
Reputation: 726599
In Java the regex would be the same, assuming that the number takes up the entire line. You could further simplify it to
^2567[78]
If you need to match a number anywhere in the string, use \b
anchor (double the backslash if you are making a string literal in Java code).
\b2567[78]
how about if there is a possibility of a
+
at the beginning of a number
Add an optional +
, like this [+]?
or like this \+?
(again, double the backslash for inclusion in a string literal).
Note that it is important to know what Java API is used with the regular expression, because some APIs will require the regex to cover the entire string in order to declare it a match.
Upvotes: 1