Java Regex match anything that matches given pattern and is not between a given character

user4149285

I have a parser that applies regex rules on a given string. The first match of each rule is removed and placed into a node.

One of the rules tries to find variables, which are in between | symbols consisting of only digits, letters, underscore and dash. The rule that does this is the following: (?:\|)[a-zA-Z0-9_-]+(?:\|)+?

For example we have the expression: part1+250+|part2|+part3 It matches on |part2| which is a variable.

Now I need another rule that matches constants, which can consist of only (digits, letters, underscore, dash and spaces). But it should not match on the variables.

Taking a look at the same example expression, it should match the following: part1,250,part3 It should match anything that is (digit, letter, space, underscore, dash) and is not between | symbols.

How can I achieve this using a single regex expression?

Mena

Here is a single-pattern implementation of your solution:

String input = "part1+250+|part2|+part3";

Pattern p = 
//                   | group 1 ("variable")
//                   | | positive look behind for "|"
//                   | |      | character class for allowed characters
//                   | |      |             | quantifier for 1+ instance, greedy
//                   | |      |             | | positive lookahead for "|"
//                   | |      |             | |      | OR
//                   | |      |             | |      || group 2 ("constant") 
//                   | |      |             | |      ||| negative lookbehind for "|"
//                   | |      |             | |      |||       | allowed chars
//                   | |      |             | |      |||       |             | quantifier
//                   | |      |             | |      |||       |             | | negative
//                   | |      |             | |      |||       |             | | lookahead
//                   | |      |             | |      |||       |             | | 
    Pattern.compile("((?<=\\|)[ a-zA-Z0-9_-]+(?=\\|))|((?<!\\|)[ a-zA-Z0-9_-]+(?!\\|))");
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.printf("Variable: %s%nConstant: %s%n", m.group(1), m.group(2));
}

Output

Variable: null
Constant: part1
Variable: null
Constant: 250
Variable: part2
Constant: null
Variable: null
Constant: part3

Notes

  • Here it prints everything, but you can of course check for nulls and infer whether a "variable", a "constant", or nothing's been found.
  • Quick solution here, so there might be edge cases not covered.
  • Grouping here is Java 6 styled for backwards compatibility. Java 7's named groups are a lot more fun though!

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

grep: regex only for match anything between parenthesis

분류에서Dev

How can I open the file with the most matches for a given regex?

분류에서Dev

How to match a word using a given character only once

분류에서Dev

How to extract items with XPath that do not match a given pattern?

분류에서Dev

Regex Match Any Character Between (Inclusive) {}

분류에서Dev

Match a given sequence only if not between quotes, taking escaped quotes into consideration

분류에서Dev

regex to search for a string that matches almost anything except a |

분류에서Dev

Remove next character jQuery (no html elements given)

분류에서Dev

find not recursive when given a pattern on the command line

분류에서Dev

Regex match for starting character or _\w

분류에서Dev

Java regex pattern matches a string when i obtain string from System.in but not when declared

분류에서Dev

Join two lines in a text file in Unix based on regex pattern matching by removing the newline character in between

분류에서Dev

Find number greater than given parameter in regex

분류에서Dev

Problems with relative layout: No resource found that matches the given name

분류에서Dev

Calculating the days between two given dates

분류에서Dev

Calculating the distance between 2 given points

분류에서Dev

java-Match a regex pattern in a string(listing matching and non-matching parts)

분류에서Dev

R regex match pattern and replace with dynamic value

분류에서Dev

How to find the multiple occurrence spacial character in the given string?

분류에서Dev

Regexp - How to check whether a string starts OR ends with given character?

분류에서Dev

sed: insert text after Nth character preceding/following a given string

분류에서Dev

Servlet filter doesn't respond on given URL pattern

분류에서Dev

How to match both UDP and TCP for given ports in one line with nftables

분류에서Dev

How to delete all files that match a pattern (or older than..) except the newest file that matches the pattern?

분류에서Dev

Unable scrape certain fields from a given string using regex

분류에서Dev

With xpath, locate an HTML element with a partial id given (possibly regex)

분류에서Dev

Regex to create a group from an entire line, or just up to a given token

분류에서Dev

Java regex match outside bracks

분류에서Dev

How to get the character index and character in given string using mouse hover in Jquery

Related 관련 기사

  1. 1

    grep: regex only for match anything between parenthesis

  2. 2

    How can I open the file with the most matches for a given regex?

  3. 3

    How to match a word using a given character only once

  4. 4

    How to extract items with XPath that do not match a given pattern?

  5. 5

    Regex Match Any Character Between (Inclusive) {}

  6. 6

    Match a given sequence only if not between quotes, taking escaped quotes into consideration

  7. 7

    regex to search for a string that matches almost anything except a |

  8. 8

    Remove next character jQuery (no html elements given)

  9. 9

    find not recursive when given a pattern on the command line

  10. 10

    Regex match for starting character or _\w

  11. 11

    Java regex pattern matches a string when i obtain string from System.in but not when declared

  12. 12

    Join two lines in a text file in Unix based on regex pattern matching by removing the newline character in between

  13. 13

    Find number greater than given parameter in regex

  14. 14

    Problems with relative layout: No resource found that matches the given name

  15. 15

    Calculating the days between two given dates

  16. 16

    Calculating the distance between 2 given points

  17. 17

    java-Match a regex pattern in a string(listing matching and non-matching parts)

  18. 18

    R regex match pattern and replace with dynamic value

  19. 19

    How to find the multiple occurrence spacial character in the given string?

  20. 20

    Regexp - How to check whether a string starts OR ends with given character?

  21. 21

    sed: insert text after Nth character preceding/following a given string

  22. 22

    Servlet filter doesn't respond on given URL pattern

  23. 23

    How to match both UDP and TCP for given ports in one line with nftables

  24. 24

    How to delete all files that match a pattern (or older than..) except the newest file that matches the pattern?

  25. 25

    Unable scrape certain fields from a given string using regex

  26. 26

    With xpath, locate an HTML element with a partial id given (possibly regex)

  27. 27

    Regex to create a group from an entire line, or just up to a given token

  28. 28

    Java regex match outside bracks

  29. 29

    How to get the character index and character in given string using mouse hover in Jquery

뜨겁다태그

보관