I have a string like "portal100common2055".
I would like to split this into two parts, where the second part should only contain numbers.
"portal200511sbet104" would become "portal200511sbet", "104"
Can you please help me to achieve this?
Like this:
Matcher m = Pattern.compile("^(.*?)(\\d+)$").matcher(args[0]);
if( m.find() ) {
String prefix = m.group(1);
String digits = m.group(2);
System.out.println("Prefix is \""+prefix+"\"");
System.out.println("Trailing digits are \""+digits+"\"");
} else {
System.out.println("Does not match");
}
String[] parts = input.split("(?<=\\D)(?=\\d+$)");
if (parts.length < 2) throw new IllegalArgumentException("Input does not end with numbers: " + input);
String head = parts[0];
String numericTail = parts[1];
This more elegant solution uses the look behind and look ahead features of regex.
Explanation:
(?<=\\D) means at the current point, ensure the preceding characters ends with a non-digit (a non-digit is expressed as \D)
(?=\\d+$) means t the current point, ensure that only digits are found to the end of the input (a digit is expressed as \d)
This will only the true at the desired point you want to divide the input
Related
How can I know if my string exactly starts with {n} number of leading zeros?
For example below, the conditions would return true but my real intention is to check if the string actually starts with only 2 zeros.
String str = "00063350449370"
if (str.startsWith("00")) { // true
...
}
You can do something like:
if ( str.startsWith("00") && ! str.startsWith("000") ) {
// ..
}
This will make sure that the string starts with "00", but not a longer string of zeros.
You can try this regex
boolean res = s.matches("00[^0]*");
How about?
final String zeroes = "00";
final String zeroesLength = zeroes.length();
str.startsWith(zeroes) && (str.length() == zeroes.length() || str.charAt(zeroes.length()) != '0')
Slow but:
if (str.matches("(?s)0{3}([^0].*)?") {
This uses (?s) DOTALL option to let . also match line-breaks.
0{3} is for 3 matches.
How about using a regular expression?
0{n}[^0]*
where n is the number of leading '0's you want. You can utilise the Java regex API to check if the input matches the expression:
Pattern pattern = Pattern.compile("0{2}[^0]*"); // n = 2 here
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
// code
}
You can use a regular expression to evaluate the String value:
String str = "00063350449370";
String pattern = "[0]{2}[1-9]{1}[0-9]*"; // [0]{2}[1-9]{1} starts with 2 zeros, followed by a non-zero value, and maybe some other numbers: [0-9]*
if (Pattern.matches(pattern, str))
{
// DO SOMETHING
}
There might be a better regular expression to resolve this, but this should give you a general idea how to proceed if you choose the regular expression path.
The long way
String TestString = "0000123";
Pattern p = Pattern.compile("\\A0+(?=\\d)");
Matcher matcher = p.matcher(TestString);
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(" Group: " + matcher.group());
}
Your probably better off with a small for loop though
int leadZeroes;
for (leadZeroes=0; leadZeroes<TestString.length(); leadZeroes++)
if (TestString.charAt(leadZeroes) != '0')
break;
System.out.println("Count of Leading Zeroes: " + leadZeroes);
I need to split string to parts by regex.
String is: AA2 DE3 or AA2 and I need this 2.
String code = "AA2 DE3";
String[] parts = code.split("^(AA(\\d)+){1}( )?(\\w*)?$");
and here length of parts is 0.
I tried
String[] parts = code.split("^((AA){1}(\\d)+){1}( )?(\\w*)?$");
but also 0.
It looks like wrong regex. Although it works fine in PHP.
edit
In fact I need to get the number after "AA" but there may be additional word after it.
Assuming that you only want to extract the number and don't care to validate the rest:
Pattern pattern = Pattern.compile("^AA(\\d+)");
Matcher matcher = pattern.matcher(code);
String id = null;
if (matcher.find()) {
id = matcher.group(1);
}
Note that I rewrite (\d)+ to (\d+) to capture all the digits. When there are more than one digit, your regex captures only the last digit.
If you want to keep your validation:
Pattern pattern = Pattern.compile("^AA(\\d+) ?\\w*$");
With String.split, the regex specifies what goes in-between the parts. In your case, your regex matches the entire string, so there is nothing else, hence it returns nothing.
If you want to match this regex, use:
Pattern pattern = Pattern.compile("^(AA(\\d)+){1}( )?(\\w*)?$");
Matcher matcher = pattern.matcher(code);
if(!matcher.matches()) {
// the string doesn't match your regex; handle this
} else {
String part1 = matcher.group(1);
String part2 = matcher.group(2);
// repeat the above line similarly for the third and forth groups
// do something with part1/part2/...
}
It is indeed better to use Pattern and Matcher APIs for this.
This is purely from academic purpose in case you must use String#split only. You can use this lookbehind based regex for split:
(?<=AA\\d{1,999}) *
Code:
String[] toks = "AA2 DE3".split( "(?<=AA\\d{1,999}) *" ); // [AA2, DE3]
OR
String[] toks = "AA2".split( "(?<=AA\\d{1,999}) *" ); // [AA2]
If you'd like String#split() to handle the Pattern/Matcher for you, you can use:
String[] inputs = { "AA2 DE3", "AA3", "BB45 FG6", "XYZ321" };
try {
for (String input : inputs) {
System.out.println(
input.split(" ")[0].split("(?=\\d+$)", 2)[1]
);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Input format is incorrect.");
}
}
Output :
2
3
45
321
If the input is guaranteed to start with AA, you can also use
System.out.println(
input.split(" ")[0].split("(?<=^AA)")[1]
);
Firstly i don't know if it's even possible. Well, I need a code which would find if in JTextArea are two or more word close to each other with the same ending (with the same two or more last letters) and auto put comma between them. For ex. "I walked played with my dog" it should fix that sentence to: "I walked, played with my dog" it should auto put comma between walked and played because they're close to each other and two last letters are the same. Can anyone help me? Thanks very much.
Regex based solution:
String inputString = "I walked played with bobby robby my dog";
Pattern p = Pattern.compile("([a-z]{2})\\s([a-z]{0,})\\1");
Matcher m = p.matcher(inputString);
while (m.find()) {
inputString = inputString.substring(0, m.start(2) - 1) + ", " + inputString.substring(m.start(2));
m = p.matcher(inputString);
}
The pattern searches for places where there are 2 letters, a space, then some more letters, then the first 2 letters again.
I tweaked the input string to prove it was working, and my output was as expected:
'I walked played with bobby robby my dog'
becomes:
'I walked, played with bobby, robby my dog'
addition: In order to increase the number of characters matched, increase the number in {2} to the desired value. If there is one specific pair you are looking for (e.g. ed) then change [a-z]{2} to be your desired characters. e.g.
Pattern p = Pattern.compile("(ed)\\s([a-z]{0,})\\1");
This should do it:
// First read the text from the text area:
String text = textArea1.getText();
// Split the string around spaces (thats enough based on your specification above)
String[] words = text.split(" ");
String lastLetters = "";
StringBuilder result = new StringBuilder();
// Go through building up the result by looking at one word at a time
for (String str: words) {
if (!lastLetters.isEmpty() && str.endsWith(lastLetters) {
result.append(", ");
} else {
result.append(" ");
}
result.append(str);
int start = str.length()-3;
if (start < 0) {
start = 0;
}
lastLetters = str.substring(start, str.length()-1);
}
// Set the result into the other text area
textArea2.setText(result.toString());
You might need to tweak some of the parameters into the subString to get the exact range of values you need, etc.
I am trying to achieve this.
I have a string of 9char (always the same). But i also know that the first and last char is always a aplhabetic, it must be. the rest in the middle are numbers. How to check for that.
I got this logic so far, syntax is my problem
string samplestring;
samplestring = a1234567B
If(samplestring.length() == 9 && samplestring.substring(0,1).uppercase && samplestring.substring(8,9) && samplestring.THE REST OF THE CHAR IN THE MIDDLE ARE DIGITS)
{
println("yes this is correct");
}
else
{
println("retype");
}
Please dont mind about the simple english just want to know the syntax but the logic is there i hope..
Also can please show me those lowercase ones how to convert to uppercase?
A regular expression would be suitable:
String s = new String("A2345678Z");
if (s.matches("[A-Z][0-9]{7}[A-Z]")))
{
}
Regular expression explained:
[A-Z] means any uppercase letter
[0-9]{7} means 7 digits
Pattern p = Pattern.compile("^[A-Za-z]\\d+[A-Za-z]$");
Matcher m = p.match("A1234567B");
if (m.matches()) {
//
}
Edit:
If there are always seven digits, you can replace the \\d+ with \\d{7}
String str="A12345678B";
char first = str.charAt(0);
char second = str.charAt(str.length()-1);
if(Character.isUpperCase(first)&& Character.isUpperCase(second)){
//do something
}
A String will be of format [( 1.0N)-195( 1.0E)-195(28)-769.7(NESW)-1080.8(U)-617.9(43-047-30127)]
I need a regex to match to see if the string contains -XXX-XXX (where X is a digit)
Pattern p = Pattern.compile("(?=.*?(?:-[0-9][0-9][0-9]-[0-9][0-9][0-9]))");
if(p.matcher(a).matches())
{
System.out.println("Matched");
}
Also I've tried -[0-9][0-9][0-9]-[0-9][0-9][0-9] and (?=.*?-[0-9][0-9][0-9]-[0-9][0-9][0-9])
Nothing worked
A substring would be much easier, but (?:\\d{2})(-\\d{3}-\\d{5}) will match -XXX-XXXXX as the 1 group.
I'm assuming the 3 digits in the last number was a mistake. If not just change the 5 to a 3.
If you want to check if the string contains -3digits-3digits
String a = "43-037-30149";
Pattern p = Pattern.compile(".*(-[0-9]{3}-[0-9]{3})");
if(p.matcher(a).matches())
{
System.out.println("Matched");
}
why don't you use substring??
String b = a.substring(2,9);
or this one:
String c = a.substring(a.indexOf('-'), a.indexOf('-') + 8);
making "only" a substring would also be much more efficient! ;)