Am I misinterpreting something regarding Java regexes? Shouldn't the following match the leading zero:
public class Testit {
public static void main(String[] args) {
format("0115724848");
}
private static void format(String elementToFormat) {
if (elementToFormat.matches("^0")) {
System.out.println("leading zero:" + elementToFormat);
} else {
System.out.println("no leading zero:" + elementToFormat);
}
}
}
matches tries to match the pattern against the whole of the input string... and your input string isn't just "beginning of string followed by 0".
Either you need "0.*" (the ^ is unnecessary precisely because matches will match the whole string) or you could create a Pattern and then use:
if (pattern.matcher(text).lookingAt())
Of course it's not clear why you're using a regex here at all, in that you can use:
if (text.startsWith("0"))
String.match wants to match the whole String, and your regex ^0 doesn't.
Instead you need a regex like: 0.*, which means a "the string begins with 0, followed by zero or more characters". Or, depending on your needs, 0\d*, which means "the string begins with 0 followed by zero or more digits", which is what your example input looks like.
if ("0115724848".matches("0\\d*"))
System.out.println("leading zero.");
This is the pattern that you should use:
^0.*
Also why not use startsWith("0") - much simpler
Check this code..It should work.
public class Testit {
public static void main(String[] args) {
format("0115724848");
}
private static void format(String elementToFormat) {
if (elementToFormat.matches("^0.*")) {
System.out.println("leading zero:" + elementToFormat);
} else {
System.out.println("no leading zero:" + elementToFormat);
}
}
}
This regex will match numbers with leading zeros, but not "0": /^0+[1-9]/
Related
Want a regex for NUMERIC(p,s) NUMERIC will always be there and I just want to check whether inside brackets my values are comma separated or not. For example NUMERIC(10,20) so my regex would also contain "NUMERIC(" and comma checking for numbers and ")"
I have tried for comma check but not able to get the NUMERIC with "(" and ")" in my regex.
I have tried with "^NUMERIC\([0-9]+(,[0-9]+)*"
public static void main(String[] args) {
String regex="^NUMERIC\\([0-9]+(,[0-9]+)*"
String v="NUMERIC(1,2)";
System.out.println(v.matches(regex));
}
The expected result is the regex which would give me true for any comma separated number value within "NUMERIC(" and ")"
.matches() expects the entire string to match, and your regex doesn't contain a token for the closing parenthesis.
If there are always two values p and s, you should use something like
public static void main(String[] args) {
String regex="NUMERIC\\([0-9]+,[0-9]+\\)"
String v="NUMERIC(1,2)";
System.out.println(v.matches(regex));
}
If the second parameter is optional:
public static void main(String[] args) {
String regex="NUMERIC\\([0-9]+(?:,[0-9]+)?\\)"
String v="NUMERIC(1)";
System.out.println(v.matches(regex));
}
See also Difference between matches() and find() in Java Regex
Use this regular exp.
^NUMERIC\([0-9]+(,[0-9]\){1})
I just modified yours.
I am facing some difficulties because of some regex expression in Java. I want a expression the validates that one or more words are valid and are delimited by semicolon or not.
Examples:
VF;VM - Good
VF;GM - Bad
VF,VM - Bad
VF;VM;IF - Good
VF,VM;IF - Bad
I tried this one:
String regex = "(\\bVM\\b|\\bVF\\b|\\bTV\\b|\\bIM\\b|\\bIF\\b)|\\;";
But it doesn't work....
If you can help me I will be thankful.
Basically, you want a list of the valid words, and then an optional repeated group starting with a ; and the list of valid words:
String regex = "^(?:\\b(?:VM|VF|TV|IM|IF)\\b)(?:;\\b(?:VM|VF|TV|IM|IF)\\b)*$";
That:
Uses ^ at the beginning and $ at the end to match the full input.
Starts with VM, VF, TV, IM, or IF with word boundary assertions on either side.
Then allows zero or more repeats with a ; in front of it. All of your examples involve at least two "words," though, so if that's a requirement, change the * (repeat zero or more times) to a + (repeat one or more times) on the second group.
...and actually, as Toto points out, since we're using anchors and defining a specific separator (;), we don't need the word boundaries, so simply
String regex = "^(?:VM|VF|TV|IM|IF)(?:;(?:VM|VF|TV|IM|IF))*$";
...is sufficient, and simpler.
Example on regex101 (as a JavaScript regex)
Tests:
class Example
{
private static String regex = "^(?:VM|VF|TV|IM|IF)(?:;(?:VM|VF|TV|IM|IF))*$";
public static void main (String[] args) throws java.lang.Exception
{
test("VF;VM", true);
test("VF;GM", false);
test("VF,VM", false);
test("VF;VM;IF", true);
test("VF,VM;IF", false);
}
private static void test(String str, boolean expectedResult) {
boolean result = str.matches(regex);
System.out.println(str + " -- " + (result ? "Good" : "Bad") + (result == expectedResult ? " - OK" : " - ERROR"));
}
}
Live on ideone
This code might be easier to understand and modify than a big RegEx.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ValidateList
{
public static void main(String[] args) {
Set<String> validWords = new HashSet<String>(Arrays.asList(new String[] { "VM", "VF", "TV", "IM", "IF" }));
System.out.println(areAllWordsValid("VF;VM;IF", validWords));
System.out.println(areAllWordsValid("VF;VM;IF;", validWords));
System.out.println(areAllWordsValid("VF;GM;IF", validWords));
}
public static boolean areAllWordsValid(String string, Set<String> validWords) {
String[] words = string.split(";", -1);
for (String word : words) {
if (!validWords.contains(word)) {
return false;
}
}
return true;
}
}
Same as the accepted answer but collapsed down a little bit:
^(?:VF|VM|IF|TV|IM|;)++$
I want to remove a numeric value from a specific position position. I have used a regex but it deletes every numeric value from the String.
I have these Strings:
Draft1(admin)
Draft2(adminn)
Draft21(admin23)
Draft112(admin211)
And I want these strings as:
Draft(admin)
Draft(adminn)
Draft(admin23)
Draft(admin211)
currently I've used regex:
name = name.replaceAll("\\d", "");
which replaces all the numeric values and I get something like:
Draft(admin)
You can simply use String#replaceFirst with regex like (?i)(?<=Draft)\d+ to delete this digits:
name = name.replaceFirst("(?i)(?<=Draft)\\d+","");
Where:
(?i) makes regex caseinsensitive, so the Draft could be even DRAFT or draft
(?<=Draft) is lookbehind for Draft word, which asserts that what immediately precedes the current position in the string is Draft
\\d+ are one or more digit to be replaced
(?<=Draft)\\d+\\b
You can use this and replace by empty string.The lookbehind will make sure it replace only numbers after Draft.
You could try this
class String111
{
public static void main(String args[])
{
String s1="Draft1(admin)";
String s2="Draft21(admin23)";
System.out.println(s1.substring(0,s1.indexOf('(')).replaceAll("\\d", "")+s1.substring(s1.indexOf('('),s1.length()));
System.out.println(s2.substring(0,s2.indexOf('(')).replaceAll("\\d", "")+s2.substring(s2.indexOf('('),s2.length()));
}
}
This works
public static void main(String[] args) {
String name = "Draft112(admin211)";
name = name.replaceAll("\\d+(?=\\()","");
System.out.println(name);
}
public static String FILL_IN_THE_BLANK_REGEX = "\\\\[blank_.+\\\\]";
public static int getBlankCountForFillInTheBlank(String questionText) {
Matcher m = Pattern.compile(FILL_IN_THE_BLANK_REGEX).matcher(questionText);
int count = 0;
while (m.find()) ++count;
return count;
}
public static void main(String[] args) {
System.out.println(getBlankCountForFillInTheBlank("abc [blank_tag1] abc [blank_tag2]")); // prints 1
}
But if I do something like
public static String FILL_IN_THE_BLANK_REGEX = "\\\\[blank_tag.\\\\]";
It prints 2 which is correct.
'+' does not work here I don't know why.
(the blank tag can be anything like [blank_someusertag])
See the javadoc for Pattern. I believe it's because + is a greedy quantifier and therefore matches everything it can. You can add a ? after the + to make it reluctant.
public static String FILL_IN_THE_BLANK_REGEX = "\\[blank_.+?\\]";
will print
2
.+ will match ANY character 1 or more times.
Use the non-greedy ? to ensure you only capture until the next defined expression.
Your working expression: \\[blank_.+?\\]
I have strings like:
Alian 12WE
and
ANI1451
Is there any way to replace all the numbers (and everything after the numbers) with an empty string in JAVA?
I want the output to look like this:
Alian
ANI
With a regex, it's pretty simple:
public class Test {
public static String replaceAll(String string) {
return string.replaceAll("\\d+.*", "");
}
public static void main(String[] args) {
System.out.println(replaceAll("Alian 12WE"));
System.out.println(replaceAll("ANI1451"));
}
}
You could use a regex to remove everyting after a digit is found - something like:
String s = "Alian 12WE";
s = s.replaceAll("\\d+.*", "");
\\d+ finds one or more consecutive digits
.* matches any characters after the digits
Use Regex
"Alian 12WE".split("\\d")[0] // Splits the string at numbers, get the first part.
Or replace "\\d.+$" with ""