In Python with Re library, I try to match a char structur with this synopsis:
[n|new|newgame] <name> [code=<code>] [type=<type>] [licence=<licence>] [url=<url>]
But code, type, licence, and url statements could appear in any order not necessary this one. Or could also not appear at all.
For the moment, I have the following code:
import re
# Adjusted regex pattern to match up to 'url' without consuming the entire line if 'url' is absent
addNewGamepattern = r'(n|new|newgame)s+(?P<name>S+)s+'
r'(?:code=(?P<code>[a-zA-Z0-9]*)s*)?'
r'(?:type=(?P<type>fps|mmorpg|rpg)s*)?'
r'(?:licence=(?P<licence>mit|gpl|cc|copyright)s*)?'
r'(?:url=(?P<url>S+)s*)?'
# List of test strings
test_strings = [
"newgame MyGame code=ABC type=fps licence=mit url=http://example.com",
"n MyGame type=rpg code=123",
"new MyGame url=http://example.com code=XYZ licence=gpl type=mmorpg",
"newgame AnotherGame code=DEF licence=cc type=mmorpg",
"newgame GameWithoutParameters"
]
# Function to test the pattern with each string
def test_pattern(pattern, strings):
for string in strings:
match = re.match(pattern, string)
if match:
print(f"String: '{string}'")
print("Match found!")
print(f"Game name: {match.group('name')}")
print(f"Code: {match.group('code') if match.group('code') else 'Not specified'}")
print(f"Type: {match.group('type') if match.group('type') else 'Not specified'}")
print(f"Licence: {match.group('licence') if match.group('licence') else 'Not specified'}")
print(f"URL: {match.group('url') if match.group('url') else 'Not specified'}")
print()
else:
print(f"String: '{string}'")
print("No match found.")
print()
# Testing the pattern with the test strings
test_pattern(addNewGamepattern, test_strings)
But it doesn’t work yet as I expect. Cause here is it output:
String: 'newgame MyGame code=ABC type=fps licence=mit url=http://example.com'
Match found!
Game name: MyGame
Code: ABC
Type: fps
Licence: mit
URL: http://example.com
String: 'n MyGame type=rpg code=123'
Match found!
Game name: MyGame
Code: Not specified
Type: rpg
Licence: Not specified
URL: Not specified
String: 'new MyGame url=http://example.com code=XYZ licence=gpl type=mmorpg'
Match found!
Game name: MyGame
Code: Not specified
Type: Not specified
Licence: Not specified
URL: http://example.com
String: 'newgame AnotherGame code=DEF licence=cc type=mmorpg'
Match found!
Game name: AnotherGame
Code: DEF
Type: Not specified
Licence: cc
URL: Not specified
String: 'newgame GameWithoutParameters'
No match found.
As you can see, the elements who are not following theire order are just ignored.
The question
How to match the optional parameters no matter their order?