Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I make a regex match for measurement units?
    text
    copied!<p>I'm building a small Java library which has to match units in strings. For example, if I have "300000000 m/s^2", I want it to match against "m" and "s^2".</p> <p>So far, I have tried most imaginable (by me) configurations resembling (I hope it's a good start)</p> <pre><code>"[[a-zA-Z]+[\\^[\\-]?[0-9]+]?]+" </code></pre> <p>To clarify, I need something that will match <code>letters[^[-]numbers]</code> (where [ ] denotes non obligatory parts). That means: letters, possibly followed by an exponent which is possibly negative.</p> <p>I have studied regex a little bit, but I'm really not fluent, so any help will be greatly appreciated!</p> <p>Thank you very much,</p> <p><strong>EDIT:</strong> I have just tried the first 3 replies</p> <pre><code>String regex1 = "([a-zA-Z]+)(?:\\^(-?\\d+))?"; String regex2 = "[a-zA-Z]+(\\^-?[0-9]+)?"; String regex3 = "[a-zA-Z]+(?:\\^-?[0-9]+)?"; </code></pre> <p>and it doesn't work... I know the code which tests the patterns work, because if I try something simple, like matching "[0-9]+" in "12345", it will match the whole string. So, I don't get what's still wrong. I'm trying with changing my brackets for parenthesis where needed at the moment...</p> <p><strong>CODE USED TO TEST:</strong></p> <pre><code>public static void main(String[] args) { String input = "30000 m/s^2"; // String input = "35345"; String regex1 = "([a-zA-Z]+)(?:\\^(-?\\d+))?"; String regex2 = "[a-zA-Z]+(\\^-?[0-9]+)?"; String regex3 = "[a-zA-Z]+(?:\\^-?[0-9]+)?"; String regex10 = "[0-9]+"; String regex = "([a-zA-Z]+)(?:\\^\\-?[0-9]+)?"; Pattern pattern = Pattern.compile(regex3); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { System.out.println("MATCHES"); do { int start = matcher.start(); int end = matcher.end(); // System.out.println(start + " " + end); System.out.println(input.substring(start, end)); } while (matcher.find()); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload