Pattern (string) allows characters only one time - java

I want to check if my string contains only allowed characters. Everything works properly for example 7B, 77B or 7BBBB, but when I input something like this 7B7 or 7BB2 it's not matching.
Everything work fine, but when integer is last character it's not working.
Could You tell me what is wrong with that code?
pattern = Pattern.compile("[0-9]*[a-f]*[A-F]*");
matcher = pattern.matcher(stNumber);
if (matcher.matches()) {...}

If you want to mix numbers and chars in a various order you need sth like:
Pattern pattern = Pattern.compile("[\\da-fA-F]*")

Why not try it this way?
// Compile this pattern.
Pattern pattern = Pattern.compile("[0-9]*[a-f]*[A-F]*[0-9]*");
// See if this String matches.
Matcher m = pattern.matcher("num123");
if (m.matches()) {
System.out.println(true);
}
Source

Are you trying to verify that the string only has digits and letters and nothing else?
If so try using the following:
pattern = Pattern.compile("^[a-z-A-Z\\d]*$");
matcher = pattern.matcher(stNumber);
if (matcher.matches()) {...}

Related

How to capture all instances with regex from a string with

I got help with a regex expression in java here: java regex to capture any number of periods within a string
This solved the issue of identifying patterns of the string, but I have been unable to figure out how to catch all instances within a body of text.
If I have a string body like this:
String body = "$tag:parent$ is the child of $tag:grand.parent$ who is the grandparent of $tag:child$"
I use the following and always catch the first $tag:*$ string, no matter which one is first the pattern gets it but within something like
final String REGEX = "\\$tag:(?:[a-z]+?\\.*){1,4}\\$";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pt.matcher(body);
if (matcher.find()) {
// do something with matcher.group() but should the group contain the all instances?
}
I have tried enclosing in () on regex101.com and it matches patterns and lists everything in a group but this doesn't work
tried the following, but this is me just trying random stuff:
"(\\$tag:(?:[a-z]+?\\.*){1,4}\\$)"
"(^\\$tag:(?:[a-z]+?\\.*){1,4}\\$)"
"(?<=(\\$tag:(?:[a-z]+?\\.*){1,4}\\$))"
I just basically want a java regex approach where I catch all the instances in some type of manner. Thanks for the assistance.
Elaborating on my comment:
Use a while loop to iterate over all matched patterns in your input, e.g.:
// note: I have simplified your pattern a bit, you probably don't need all
// those restrictions
Pattern pattern = Pattern.compile("\\$tag:.+?\\$");
Matcher matcher = pattern.matcher(body);
while (matcher.find()) {
// TODO whatever you want with the matched group
System.out.println(matcher.group());
}
Output
$tag:parent$
$tag:grand.parent$
$tag:child$

Pattern Matcher Vs String Split, which should I use?

First time posting.
Firstly I know how to use both Pattern Matcher & String Split.
My questions is which is best for me to use in my example and why?
Or suggestions for better alternatives.
Task:
I need to extract an unknown NOUN between two known regexp in an unknown string.
My Solution:
get the Start and End of the noun (from Regexp 1&2) and substring to extract the noun.
String line = "unknownXoooXNOUNXccccccXunknown";
int goal = 12 ;
String regexp1 = "Xo+X";
String regexp2 = "Xc+X";
I need to locate the index position AFTER the first regex.
I need to locate the index position BEFORE the second regex.
A) I can use pattern matcher
Pattern p = Pattern.compile(regexp1);
Matcher m = p.matcher(line);
if (m.find()) {
int afterRegex1 = m.end();
} else {
throw new IllegalArgumentException();
//TODO Exception Management;
}
B) I can use String Split
String[] split = line.split(regex1,2);
if (split.length != 2) {
throw new UnsupportedOperationException();
//TODO Exception Management;
}
int afterRegex1 = line.indexOf(split[1]);
Which Approach should I use and why?
I don't know which is more efficient on time and memory.
Both are near enough as readable to myself.
I'd do it like this:
String line = "unknownXoooXNOUNXccccccXunknown";
String regex = "Xo+X(.*?)Xc+X";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(line);
if (m.find()) {
String noun = m.group(1);
}
The (.*?) is used to make the inner match on the NOUN reluctant. This protects us from a case where our ending pattern appears again in the unknown portion of the string.
EDIT
This works because the (.*?) defines a capture group. There's only one such group defined in the pattern, so it gets index 1 (the parameter to m.group(1)). These groups are indexed from left to right starting at 1. If the pattern were defined like this
String regex = "(Xo+X)(.*?)(Xc+X)";
Then there would be three capture groups, such that
m.group(1); // yields "XoooX"
m.group(2); // yields "NOUN"
m.group(3); // yields "XccccccX"
There is a group 0, but that matches the whole pattern, and it's equivalent to this
m.group(); // yields "XoooXNOUNXccccccX"
For more information about what you can do with the Matcher, including ways to get the start and end positions of your pattern within the source string, see the Matcher JavaDocs
You should use String.split() for readability unless you're in a tight loop.
Per split()'s javadoc, split() does the equivalent of Pattern.compile(), which you can optimize away if you're in a tight loop.
It looks like you want to get a unique occurrence. For this do simply
input.replaceAll(".*Xo+X(.*)Xc+X.*", "$1")
For efficiency, use Pattern.matcher(input).replaceAll instead.
In case you input contains line breaks, use Pattern.DOTALL or the s modifier.
In case you want to use split, consider using Guava's Splitter. It behaves more sane and also accepts a Pattern which is good for speed.
If you really need the locations you can do it like this:
String line = "unknownXoooXNOUNXccccccXunknown";
String regexp1 = "Xo+X";
String regexp2 = "Xc+X";
Matcher m=Pattern.compile(regexp1).matcher(line);
if(m.find())
{
int start=m.end();
if(m.usePattern(Pattern.compile(regexp2)).find())
{
final int end = m.start();
System.out.println("from "+start+" to "+end+" is "+line.substring(start, end));
}
}
But if you just need the word in between, I recommend the way Ian McLaird has shown.

Java regex pattern for number

I know that this question can be stupid but I am trying to get some information from text and you are my last hope after last three hours of trying..
DIC: C/40764176 IC: 407641'6
Dekujerne a t8ime se na shledanou
I need to get for example this 40764176
I need to get string with 8-10 length, sometimes there can be some special chars like I,i,G,S,O,ó,l) but I have tried a lot of patterns for this and no one works...
I tried:
String generalDicFormatPattern = "([0-9IiGSOól]{8,10})";
String generalDicFormatPattern = ".*([0-9IiGSOól]{8,10}).*";
String generalDicFormatPattern = "\\b([0-9IiGSOól]{8,10})\\b";
nothing works... do you know where is the problem?
edit:
I use regex in this way:
private List<String> getGeneralDicFromLine(String concreteLine) {
List<String> allMatches = new ArrayList<String>();
Pattern pattern = Pattern.compile(generalDicFormatPattern);
Matcher matcher = pattern.matcher(concreteLine);
while (matcher.find()) {
allMatches.add(matcher.group(1));
}
return allMatches;
}
If your string's pattern is fixed you can use the regex
C/([^\s]{8,10})\sIC:
Sample code:
String s = "DIC: C/40764176 IC: 407641'6";
Pattern p = Pattern.compile("C/([^\\s]{8,10})\\sIC:");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group(1)); // 40764176
}
I'm expecting any character (includes the special ones you've shown in examples) but a white space.
May be you can split your string with spaces (string.split('\\s');), then you should have an array like this :
DIC:
C/40764176
IC: 407641'6
...
shledanou
Get the second string, split it using '/', and get the second element.
I hope it helped you.
Tip : you can check after the result using a regex (([0-9IiGSOól]{8,10})

Get negative int from String, also containing letters, in Java

I've found something which almost fit my needs here
Integer.parseInt(s.replaceAll("[\\D]", ""))
but I can't find out how should I modify this to get negative integer. Sample string is:
"some\\-2c.st"
and I need to extract "-2"
I'd do it the other way around, look for the integer instead of stripping the rest:
String str = "some\\-2c.st";
Pattern pattern = Pattern.compile("-?[0-9]+");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
int value = Integer.parseInt(matcher.group());
System.out.println(value);
}
Integer.parseInt(s.replaceAll("[^\\d-]", ""))
You can remove everything you don't want, or you can extract that what you want.
It seems, the latter is more appropriate here, you can use a regex like (-?\d+) to do it.

forming correct regular expression in dynamic string

I have a FileInputStream who reads a file which somewhere contains a string subset looking like:
...
OperatorSpecific(XXX)
{
Customer(someContent)
SaveImage()
{
...
I would like to identify the Customer(someContent) part of the string and switch the someContent inside the parenthesis for something else.
someContent will be a dynamic parameter and will contain a string of maybe 5-10 chars.
I have used regEx before, like once or twice, but I feel that in a context such as this where I don't know what value will be inside the parenthesis I'm at a loss of how I should express it...
In summary I want to have a string returned to me which has my someContent value inside the Customer-parenthesis.
Does anyone have any bright ideas of how to get this done?
Try this one (double the escaping backslashes for the use in java!)
(?<=Customer\()[^\)]*
And replace with your content.
See it here at Regexr
(?<=Customer\() is look behind assertion. It checks at every position if there is a "Customer(" on the left, if yes it matches on the right all characters that are not a ")" with the [^\)]*, this is then the part that will be replaced.
Some working java code
Pattern p = Pattern.compile("(?<=Customer\\()[^\\)]*");
String original = "Customer(someContent)";
String Replacement = "NewContent";
Matcher m = p.matcher(original);
String result = m.replaceAll(Replacement);
System.out.println(result);
This will print
Customer(NewContent)
Using groups works and non-greedy works:
String s =
"OperatorSpecific(XXX)\n {\n" +
" Customer(someContent)\n" +
" SaveImage() {";
Pattern p = Pattern.compile("Customer\\((.*?)\\)");
Matcher matcher = p.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
will print
someContent
Untested, but something like the following should work:
Pattern pattern = Pattern.compile("\\s+Customer\\(\\s*(\\w+)\\s*\\)\\s*");
Matcher matcher = pattern.matcher(input);
matcher.matches();
System.out.println(matcher.group(1));
EDIT
This of course won't work with all possible cases:
// legal variable names
Customer(_someContent)
Customer($some_Content)

Categories

Resources