By xRoby


2019-02-11 09:05:42 8 Comments

I want to check if a string: String s = "a=182 b=41 c=72", contains only: a b c, with their respective values, but they can occur in random order. How do I go about doing this?

I have tried doing the following: (?=a\\=(\\d+))\\s+(?=b\\=(\\d+))\\s+(?=c\\=(\\d+))

2 comments

@Potatoツ 2019-02-11 09:16:47

Try this regex:

^(?:(\\s*[abc]=)(?!.*\\1)\\d+){3}$

Click for Demo

JAVA Code

Explanation:

  • ^ - asserts the start of the line
  • (?:(\\s*[abc]=)(?!.*\\1)\\d+){3}
    • (\\s*[abc]=) - matches 0+ occurrences of a whitespace followed by either a or b or c followed by =. This whole submatch is captured in Group 1.
    • (?!.*\\1) - negative lookahead to make sure that the current match is not followed by the contents of group 1 anywhere later in the string
    • \\d+ - matches 1+ digits
    • {3} - repeats the subpattern 3 times once each for a, b, c
  • $ - asserts the end of the line

@Wiktor Stribiżew 2019-02-11 09:26:04

Just in case spaces can be missing, then the ^(?:(\\s*[abc]=)(?!.*\\1)\\d+){3}$ regex will also match a=182 b=41b=72

@Potatoツ 2019-02-11 09:33:19

@WiktorStribiżew I can avoid that if I modify the pattern to ^([abc]\s*=)(?!.*\1)\d+(?:\s+([abc]\s*=)(?!.*\2)\d+){2}$

@Manzurul Hoque Rumi 2019-02-11 09:13:58

If your string always contain space you can split them into array like this

String[] words = s.split(" ");

and then check first char of each array element.

Related Questions

Sponsored Content

26 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1834788 View
  • 2141 Score
  • 26 Answer
  • Tags:   java arrays

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3833149 View
  • 3283 Score
  • 65 Answer
  • Tags:   java random integer

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

56 Answered Questions

[SOLVED] How to replace all occurrences of a string?

35 Answered Questions

26 Answered Questions

[SOLVED] How to get an enum value from a string value in Java?

  • 2009-03-02 22:56:34
  • Malachi
  • 1019805 View
  • 1843 Score
  • 26 Answer
  • Tags:   java enums

43 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

31 Answered Questions

[SOLVED] Removing whitespace from strings in Java

  • 2011-03-28 07:22:01
  • zyamat
  • 1104260 View
  • 634 Score
  • 31 Answer
  • Tags:   java whitespace

33 Answered Questions

[SOLVED] How to split a string in Java

  • 2010-08-14 03:01:53
  • riyana
  • 3619537 View
  • 1515 Score
  • 33 Answer
  • Tags:   java string

18 Answered Questions

[SOLVED] How do you use a variable in a regular expression?

  • 2009-01-30 00:11:05
  • JC Grubbs
  • 642032 View
  • 1194 Score
  • 18 Answer
  • Tags:   javascript regex

Sponsored Content